본문 바로가기
개발/Java

[JAVA] 파일 생성, 삭제, 쓰기, 이름변경, 이동, 복사, 읽기 하기

by 코딩하는 흰둥이 2024. 5. 21.
반응형
파일 생성
import java.io.File;

public class FileUtil {

    public static void main(String args[]) throws Exception{
        try{
            // 만들 파일 이름 및 경로 지정
            File file = new File("src/main/resources/config/config.txt");
            file.createNewFile();
            
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

 

file.createNewFile() 을 이용하면 해당 경로에 파일을 만들 수 있는데

파일이 존재하는 경우 파일이 다시 만들어지지 않기 때문에 파일 여부를 확인하여야 한다

 

 

파일 생성 - 파일 여부 확인 및 파일 삭제
import java.io.File;

public class FileUtil {

    public static void main(String args[]) throws Exception{
        try{
            // 만들 파일 이름 및 경로 지정
            File file = new File("src/main/resources/config/config.txt");

            // 파일 여부 확인
            if(!file.exists()){
                // 파일 생성
                file.createNewFile();
            }else {
                // 파일 지우기
                file.delete();
                // 파일 생성
                file.createNewFile();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

 

 

파일에 데이터 쓰기
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;

public class FileUtil {

    public static void main(String args[]) throws Exception{
        try{
            // 만들 파일 이름 및 경로 지정
            File file = new File("src/main/resources/config/config.txt");

            // 파일 생성
            file.createNewFile();
            
            //생성된 파일에 Buffer 를 사용하여 텍스트 입력
            FileWriter fw = new FileWriter(file);
            BufferedWriter writer  = new BufferedWriter(fw);

            // 데이터 입력
            writer.write("테스트 문구");

            // Bufferd 종료
            writer.close();

        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

 

 

파일 - 이름변경
import java.io.File;

public class FileUtil {

    public static void main(String args[]) throws Exception{
        try{
            // 만들 파일 이름 및 경로 지정
            File file = new File("src/main/resources/config/config.txt");

            // 파일 여부 확인
            if(!file.exists()){
                // 파일 생성
                file.createNewFile();
            }else{
            	// 변경할 파일이름 및 경로
                File newFile = new File("src/main/resources/config/config222.txt");
                // renameTo 은 boolean 타입 
                boolean result = file.renameTo(newFile);
                System.err.println("변경 성공 여부 : " + result);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

 

 

파일 이동
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

public class FileUtil {

    public static void main(String args[]) throws Exception {
        try {
            // 원래 파일 경로
            Path originalFile = Paths.get("src/main/resources/config/config.txt");
            // 이동하려는 경로 및 파일이름 지정
            Path newFile = Paths.get("src/main/resources/config2/config.txt");

            // 파일 이동 - 이동하려는 경로에 동일한 파일이 있다면 오류가 발생한다.
            //Files.move(originalFile , newFile);

            // 이동하려는 파일이 이미 있다면 StandardCopyOption.REPLACE_EXISTING 옵션으로 덮어쓰기가 된다
            Files.move(originalFile , newFile , StandardCopyOption.REPLACE_EXISTING);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

 

파일 복사
import java.io.File;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class FileUtil {

    public static void main(String args[]) throws Exception {
        try {
            // 만들 파일 이름 및 경로 지정
            File file = new File("src/main/resources/config/config.txt");

            // 파일 여부 확인
            if (!file.exists()) {
                // 파일 생성
                file.createNewFile();
            } else {
                // 복사하려는 파일이름에 현재 시간을 붙이려고 한다
                LocalDateTime now = LocalDateTime.now();
                String formatter = now.format(DateTimeFormatter.ofPattern("yyyyMMdd HH.mm.ss"));

                // 복사하려는 경로 및 파일이름 지정
                File newFile = new File("src/main/resources/config/config_" + formatter + ".txt");

                // 파일 복사 - 파일 이름이 중복되면 오류가 발생한다.
                //Files.copy(file.toPath() , newFile.toPath());

                // 파일 복사 - 파일이 이미 있다면 StandardCopyOption.REPLACE_EXISTING 옵션으로 덮어쓰기가 된다
                Files.copy(file.toPath() , newFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

 

파일 읽기
import java.io.File;
import java.io.FileReader;
import java.nio.file.Files;
import java.nio.file.Paths;

import java.util.List;
import java.util.Scanner;

public class FileUtil {

    public static void main(String args[]) throws Exception {
        // 1. 한글자씩 읽기
        FileReader reader = new FileReader("src/main/resources/config/config.txt");
        int c;
        while ((c = reader.read()) != -1) {
            //1:일
            //2:이
            //3:삼
            //4:사
            System.out.print((char) c);
        }
        
        // 2. 라인 단위로 읽기
        Scanner scanner = new Scanner(new File("src/main/resources/config/config.txt"));
        while (scanner.hasNextLine()) {
            String str = scanner.nextLine();
            //1:일
            //2:이
            //3:삼
            //4:사
            System.out.println(str);
        }

        // 3. List 로 읽기
        List<String> lines = Files.readAllLines(Paths.get("src/main/resources/config/config.txt"));
        // [1:일, 2:이, 3:삼, 4:사]
        System.out.println(lines);
        
        // 4. String 으로 읽기
        String str = Files.readString(Paths.get("src/main/resources/config/config.txt"));
        //1:일
        //2:이
        //3:삼
        //4:사
        System.out.println(str);
    }
}

 

 

적용 - 파일 생성, 복사, 쓰기
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

public class FileUtil {

    public static void main(String args[]) throws Exception {
        // 사용자로부터 받은 임의 데이터
        Map<String, Object> testMap = new HashMap<>();
        testMap.put("1", "일");
        testMap.put("2", "이");
        testMap.put("3", "삼");
        testMap.put("4", "사");

        try{
            // 만들 파일 이름 및 경로 지정
            File file = new File("src/main/resources/config/config.txt");

            // 파일 여부 확인
            if(!file.exists()){
                // 파일 생성
                file.createNewFile();
            }else {
                // 복사하려는 파일이름에 현재 시간을 붙이려고 한다
                LocalDateTime now = LocalDateTime.now();
                String formatter = now.format(DateTimeFormatter.ofPattern("yyyyMMdd HH.mm.ss"));

                // 복사하려는 경로 및 파일이름 지정
                File newFile = new File("src/main/resources/config/config_" + formatter + ".txt");

                // 파일 복사 - 파일이 이미 있다면 StandardCopyOption.REPLACE_EXISTING 옵션으로 덮어쓰기가 된다
                Files.copy(file.toPath() , newFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
            }

            //생성된 파일에 Buffer 를 사용하여 텍스트 입력
            FileWriter fw = new FileWriter(file);
            BufferedWriter writer  = new BufferedWriter(fw);

            for(String key : testMap.keySet()){
                // 데이터 입력
                writer.write(key+":"+testMap.get(key)+"\n");
            }
            // Bufferd 종료
            writer.close();

        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

 

 

가정)

1. 사용자로부터 받은 Map 데이터를 txt 파일로 만들려고 한다.

 

2. 파일이 존재하고 있으면 원래 파일이름에 현재시간을 붙여서 파일을 복사하고

사용자로부터 받은 데이터로 txt파일을 만든다.

 

3. txt에는 '예) 1:일 ' 이런식으로 데이터를 넣는다.

writer.write(key+":"+testMap.get(key)+"\n");

 

 

댓글