파일 읽고 쓰기

이규은·2021년 10월 26일
0

자바 I/O

목록 보기
7/7

파일 읽기

FileReader

FileReader는 character 파일을 읽을 수 있는 기능을 제공한다.

FileReader reader = new FileReader("D://test.txt");
int a;

while ((a = reader.read()) != -1) {
    System.out.print((char)a);
}

read()는 한글자씩 읽어서 하나의 char를 리턴한다.
더이상 읽을 글자가 없으면 -1을 리턴한다.

BufferedReader

BufferReader는 buffer를 사용하기 때문에 FileReader보다 좀 더 효율적으로 파일을 읽을수 있다.

BufferedReader reader = new BufferedReader(new FileReader("d:\\test.txt"));
String str;
while ((str = reader.readLine()) != null) {
    System.out.println(str);
}
reader.close();

Scanner

Scanner 클레스를 이용하여 파일의 텍스트를 읽어올 수 있다.

Scanner scanner = new Scanner(new File("d:\\test.txt"));
while (scanner.hasNext()) {
    String str = scanner.next();
    System.out.println(str);
}

File

File 클래스는 모두 static 메소드로 구성 되어있다.
File 클래스를 이용하면 텍스트 파일 내용을 List나 String에 쉽게 답을 수 있다.

List<String> stringList = Files.readAllLines(Paths.get("d:\\test.txt"));
System.out.println(stringList);

파일 쓰기

BufferWriter

마지막에 close()를 호출해야한다.

public class WriteStudy {
    public static void main(String[] args) throws IOException {
        File file = new File("D://asdf.txt");
        String str = "Hello world!";

        try {
            BufferedWriter writer = new BufferedWriter(new FileWriter(file));
            writer.write(str);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

PrintWriter

print()로 여러번의 텍스트를 입력할 수 있다. 마지막에 close()를 호출해야한다.

public class WriteStudy {
    public static void main(String[] args) throws IOException {
        File file = new File("D://asdf.txt");
        try {
            FileWriter fileWriter = new FileWriter(file);
            PrintWriter printWriter = new PrintWriter(fileWriter);
            printWriter.print("Hello World!!!!");
            printWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

FileOutputStream

String을 Byte로 변환하여 스트림에 써야한다.

public class WriteStudy {
    public static void main(String[] args) throws IOException {
        File file = new File("D://abc.txt");
        String str = "Hello World";
        byte[] bytes = str.getBytes();

        try {
            FileOutputStream outputStream = new FileOutputStream(file);
            outputStream.write(bytes);
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Files

String을 byte로 변환하여 write()의 인자로 전달하면 된다.

public class WriteStudy {
    public static void main(String[] args) {
        String str = "Hello";
        byte[] bytes = str.getBytes();
        Path path = Paths.get("D://wow.txt");
        try {
            Files.write(path, bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
profile
안녕하세요

0개의 댓글