[Java] File 복사 기능 구현

JTI·2023년 1월 19일
0

📌 Code list

목록 보기
44/55
post-thumbnail

✏️ File 복사하기

  1. 원본 파일 표시
  2. 복사본 파일 표시
  3. 복사하기
import javax.swing.*;
import java.io.*;

public class FileCopy {
    public static JFileChooser chooser = new JFileChooser();
    public static File oriFile;
    public static File copyFile;
    
    // 원본 path 출력
    public static void origInfo() {

        int choice = chooser.showOpenDialog(null);

        if(choice == JFileChooser.APPROVE_OPTION) {
            oriFile = chooser.getSelectedFile();

            System.out.println(oriFile.getPath());
        }
    }
    // 복사본 path 출력
    public static void copyInfo() {
        int choice = chooser.showSaveDialog(null);

        if(choice == JFileChooser.APPROVE_OPTION) {
            copyFile = chooser.getSelectedFile();

            System.out.println(copyFile.getPath());
        }
    }
    // 복사 메서드
    public static void copy() {
        FileInputStream fis = null;
        InputStreamReader isr = null;
        BufferedReader br = null;

        FileOutputStream fos = null;
        PrintWriter pw = null;

        try {
            fis = new FileInputStream(oriFile); // 원본파일 읽기
            isr = new InputStreamReader(fis);
            br = new BufferedReader(isr);

            pw = new PrintWriter(new FileOutputStream(copyFile)); // 복사본을 붙인다.

            String line = "";
            while( (line = br.readLine()) != null ) {
                pw.write(line);
            }
            pw.flush();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtil.closeAll(br, pw);
        }

    }

    public static void main(String[] args) {
        origInfo();
        copyInfo();
        copy();
    }

}
profile
Fill in my own colorful colors🎨

0개의 댓글