[Java] 파일 생성, 파일 읽기(File, FileReader. FileWriter)

이전에 자바에서 파일과 디렉터리를 추상화한 File 클래스에 대해 정리했었는데,

이번에는 생성한 파일에 내용을 작성하는 것에 대해 정리합니다.


1. 파일 생성 및 쓰기(FileWriter, BufferedWriter)

D:\MyWork 경로 하위에 Test.txt 파일을 생성하고 내용을 작성합니다.

FileWriter의 생성자는 두번째 인자로 boolean 타입을 받는데, 이는 파일에 내용을 이어붙혀서 작성할지 처음부터 덮어씌워서 작성할지 여부를 결정합니다. 디폴트는 덮어씌워 작성입니다. (기존 내용이 날아감)

BufferedWriter는 파일에 문자열을 쓰기위해 편리한 메소드를 제공합니다. 예를들면 newLine() 처럼 줄바꿈을 추가할 수 있죠.

public class FileWriterTest {
    public static void main(String[] args) throws IOException{
        String filePath = "D:/MyWork/Test.txt";

        File file = new File(filePath); // File객체 생성
        if(!file.exists()){ // 파일이 존재하지 않으면
            file.createNewFile(); // 신규생성
        }

        // BufferedWriter 생성
        BufferedWriter writer = new BufferedWriter(new FileWriter(file, true));

        // 파일에 쓰기
        writer.write("하이루!");
        writer.newLine();
        writer.write("반가워!");
        writer.newLine();

        // 버퍼 및 스트림 뒷정리
        writer.flush(); // 버퍼의 남은 데이터를 모두 쓰기
        writer.close(); // 스트림 종료
    }
}
하이루!
반가워!

2. 파일 읽기(FileReader, BufferedReader)

1번에서 작성한 내용을 읽어 콘솔에 출력하는 예제입니다. 파일을 읽기위해 FileReader, 한줄 단위로 읽어오는 편리한 readLine() 메소드를 사용하기 위해 BufferedReader를 사용했습니다.

public class FileReaderTest {
    public static void main(String[] args) throws IOException{
        String filePath = "D:/MyWork/Test.txt";

        File file = new File(filePath); // File객체 생성
        if(file.exists()){ // 파일이 존재하면
            BufferedReader reader = new BufferedReader(new FileReader(file));

            System.out.println("파일내용 출력------------------");
            String line = null;
            while ((line = reader.readLine()) != null){
                System.out.println(line);
            }
            System.out.println("------------------------------");

            reader.close();
        }
    }
}

 

 


 

 

 

 

 

 

StringTokenizer 기본 및 사용법

StringTokenizer 클래스는 문자열을 구분자를 이용하여 쪼갤 때 사용할 수 있다. (쪼갠다. = 파싱한다.)

예를 들어 "Hi I'm Yangs!!" 라는 문자열을 " "(공백)을 구분자로 "HI", "I'm", "Yangs!!" 이렇게 3개로 쪼개는 것이 가능하다.

Token을 구분자에 의해 쪼개진 단어라고 생각하면 된다.

 

StringTokenizer 생성

- StringTokenizer(String str) : 파싱 할 문자열을 인자로 받는다. 구분자를 지정하지 않았으므로 스페이스, 탭, 줄바꿈, 캐리지 리턴 등 기본 구분자가 적용된다.

- StringTokenizer(String str, String delim) : 파싱할 문자열과 구분자를 인자로 받는다.

- StringTokenizer(String str, String delim, boolean flag) : flag는 구분자 자체도 토큰으로 인식하게 할지 여부를 정한다. 예를 들어 true라면 "Hi I'm Yangs!!"는 공백을 포함하여"HI", " ", "I'm", " ", "Yangs!!" 이렇게 5개의 토큰으로 파싱 된다.

String source = "Hi I'm Yangs!!";

StringTokenizer tokenizer1 = new StringTokenizer(source);
while(tokenizer1.hasMoreTokens()){
    System.out.println("tokenizer1's token : " + tokenizer1.nextToken());
}

StringTokenizer tokenizer2 = new StringTokenizer(source, " ");
while(tokenizer2.hasMoreTokens()){
    System.out.println("tokenizer2's token : " + tokenizer2.nextToken());
}

StringTokenizer tokenizer3 = new StringTokenizer(source, " ", true);
while(tokenizer3.hasMoreTokens()){
    System.out.println("tokenizer3's token : " + tokenizer3.nextToken());
}
// 출력결과
tokenizer1's token : Hi
tokenizer1's token : I'm
tokenizer1's token : Yangs!!

tokenizer2's token : Hi
tokenizer2's token : I'm
tokenizer2's token : Yangs!!

tokenizer3's token : Hi
tokenizer3's token :  
tokenizer3's token : I'm
tokenizer3's token :  
tokenizer3's token : Yangs!!

StringTokenizer 사용법

StringTokenizer를 이용하여 문자열 -> 배열로 파싱하기

가장 많이 사용되는 문자열을 파싱하여 배열에 담는 예제이다.

hasMoreTokens()로 총토큰의 개수를 구하고, nextToken()으로 한 토큰씩 꺼낼 수 있다.

StringTokenizer는 구분자에 의해서 파싱 후 빈 토큰은 버리는 동작을 확인할 수 있다.

String source = "|문자열||에서|배열로|갑니다|";

// StringTokenizer 생성
StringTokenizer tokenizer = new StringTokenizer(source, "|");
System.out.println("총 토큰 갯수 : " + tokenizer.countTokens()); // 총 토큰 갯수 : 4

String[] arr = new String[4]; // 결과 배열
int idx = 0;
while (tokenizer.hasMoreTokens()){
    arr[idx] = tokenizer.nextToken(); // 배열에 한 토큰씩 담기
    idx++;
}

System.out.println(Arrays.toString(arr)); // [문자열, 에서, 배열로, 갑니다]

 

 

여러 구분자로 파싱하기

StringTokenizer 생성자 구분자를 여러 개 지정하면 된다. > new StringTokenizer(source, ",|;!")

String source = "|문자열,,에서|배열로;갑니다!";

StringTokenizer tokenizer = new StringTokenizer(source, ",|;!");
System.out.println("총 토큰 갯수 : " + tokenizer.countTokens()); // 총 토큰 갯수 : 4

String[] arr = new String[4];
int idx = 0;
while (tokenizer.hasMoreTokens()){
    arr[idx] = tokenizer.nextToken();
    idx++;
}

System.out.println(Arrays.toString(arr)); // [문자열, 에서, 배열로, 갑니다]

 

 


 

 

[Java] File 클래스 기본

Java.io.File 클래스는 자바에서 파일시스템의 파일이나 디렉터리(폴더)를 추상화 한 클래스이다.

즉, File 클래스를 통하여 파일시스템의 파일이나 디렉터리를 조작(삭제, 파일명변경 등)을 할 수 있다.

 

File 클래스를 통해 할 수 있는 작업이 많은 만큼 제공되는 메소드들도 다양하다. File 클래스의 생성과 케이스별 사용법에 대해 정리한다.

 


File 객체 생성

아래 경로처럼 Test.txt 파일을 생성하고 이 파일의 File 객체를 생성한다.

D:\MyWork\Test.txt

public class File_Practice {
    public static void main(String[] args) {
        String parentPath = "D:/MyWork";
        String filePath = "D:/MyWork/Test.txt";
        String fileNm = "Test.txt";

        // File(File parent, String child) 생성자
        File file1 = new File(parentPath, fileNm);

        // File(String pathname) 생성자
        File file2 = new File(filePath);

        // File(String parent, String child) 생성자
        File parent = new File(parentPath);
        File file3 = new File(parent, fileNm);

        if(file1.exists() && file2.exists() && file3.exists()){
            System.out.println("모두 생성 완료!");
        }
    }
}

file.exist() 는 파일의 존재여부를 검사하는 메소드를 이처럼 File 클래스에서는 파일에 관한 여러 편리한 메소드를 제공하도 있다.

아래부터는 이런 메소드들을 활용하여 어떤 작업을 할 수 있는지 케이스별로 살펴본다.


File 객체 활용

아래 소스코드를 실행하기 위한 디폴트 폴더/파일 구성은 아래와 같습니다.

D:/MyWork (Dir)
D:/MyWork/Test.txt (File)
D:/MyWork/MyDirectory (Dir)

1. 파일 또는 디렉터리의 존재유무 확인 및 기본정보 출력

public class Check_Default_Info {
    public static void main(String[] args) {
        String rootPath = "D:/MyWork";

        File rootDir = new File(rootPath);

        // 파일명
        System.out.println(rootDir.getName()); // MyWork

        // 절대경로
        System.out.println(rootDir.getAbsolutePath()); // D:\MyWork

        // 경로
        System.out.println(rootDir.getPath()); // D:\MyWork

        // 존재여부
        System.out.println(rootDir.exists()); // true

        // 읽기/쓰기/실행 가능여부
        if (rootDir.exists()) { // 존재하면
            System.out.println(rootDir.canRead()); // true
            System.out.println(rootDir.canWrite()); // true
            System.out.println(rootDir.canExecute()); // true
        }
    }
}

 


2. 디렉터리의 내부 내용물(파일, 디렉터리) 출력

디렉터리의 경우 listFiles() 메소드로 내부 파일(디렉터리 포함) 목록을 가져올 수 있으며 for문으로 순회하며 작업을 할 수 있다.

public class Check_DirectoryContents_Info {
    public static void main(String[] args) {
        String rootPath = "D:/MyWork";
        File rootDir = new File(rootPath);

        if(rootDir.isDirectory()){ // 디렉터리면
            File[] contents = rootDir.listFiles(); // 파일목록을 가져온다.
            for(File file : contents){
                System.out.println("파일명 : " + file.getName());
                System.out.println("절대경로 : " + file.getAbsolutePath());
                System.out.println("파일여부 : " + file.isFile());
                System.out.println("------------------------------");
            }
        }
    }
}
// 출력결과
파일명 : MyDirectory
절대경로 : D:\MyWork\MyDirectory
파일여부 : false
------------------------------
파일명 : Test.txt
절대경로 : D:\MyWork\Test.txt
파일여부 : true
------------------------------

3. 디렉터리 및 파일 생성

mkdir() 메소드를 사용하여 디렉터리를 생성한다. mkdirs() 메소드도 제공되며 차이점은 mkdirs()는 필요한 상위의 디렉터리가 없으면 같이 만든다는 것에 있다.

createNewFile() 메소드는 신규 파일을 생성할 수 있다. 

length() 메소드는 파일의 용량을 체크할 수 있으며 신규 파일의 경우 빈 파일이므로 0이 출력된다.

public class Mkdir {
    public static void main(String[] args) {
        String rootPath = "D:/MyWork";
        File rootDir = new File(rootPath);

        // 디렉터리 생성시작
        File newDir = new File(rootDir, "newDir"); // 생성할 디렉터리
        System.out.println("신규 디렉터리 생성여부 : " + newDir.exists()); // false

        boolean isMake = newDir.mkdir(); // 디렉터리 생성
        System.out.println("신규 디렉터리 생성결과 : " + isMake); // true
        System.out.println("신규 디렉터리 생성여부1 : " + newDir.exists()); // true
        System.out.println("신규 디렉터리 생성여부2 : " + newDir.isDirectory()); // true

        // 파일 생성시작
        File newFile = new File(newDir, "newFile");
        System.out.println("신규 파일 생성여부 : " + newFile.exists()); // false

        try {
            newFile.createNewFile(); // 파일생성
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("신규 파일 생성여부 : " + newFile.exists()); // true
        System.out.println("신규 파일 용량 : " + newFile.length()); // 0
        System.out.println("신규 파일 경로 : " + newFile.getAbsolutePath()); // D:\MyWork\newDir\newFile
    }
}

 


4. 파일명 변경 및 삭제

createNewFile()로 새로운 파일 생성 후 delete() 메소드로 삭제한다.

public class Rename_Delete {
    public static void main(String[] args) throws IOException {
        String rootPath = "D:/MyWork";
        File rootDir = new File(rootPath);

        File file = new File(rootDir, "tmpFile");
        file.createNewFile();
        System.out.println("삭제전 파일 존재여부 : " + file.exists()); // true

        // 파일삭제 시작
        boolean isDel = file.delete();
        System.out.println("파일 삭제 여부 : " + isDel); // true
        System.out.println("삭제후 파일 존재여부 : " + file.exists()); // false
    }
}

 


 

+ Recent posts