-
Notifications
You must be signed in to change notification settings - Fork 0
파일 입출력
Im Sejin edited this page Mar 13, 2019
·
2 revisions
package practice.io;
import java.io.*;
public class ReaderClass {
String path = null;
public ReaderClass(String path) {
this.path = path;
}
public String read() throws IOException {
BufferedReader br = new BufferedReader(new FileReader(path));
String text = "";
while(true) {
String line = br.readLine();
if(line == null) break;
text += line + "\r\n"; // readLine()은 개행문자를 읽지 못하기에 직접 추가한다
}
br.close();
return text;
}
public String readByte() throws IOException {
FileInputStream fis = new FileInputStream(path);
byte[] b = new byte[1024]; // 1024바이트 만큼씩 읽는다
fis.read(b);
fis.close();
return new String(b); // 바이트를 String constructor를 통해 바꾼다
}
}
java.io.Reader
─BufferedReader
└InputStreamReader
─FileReader
BufferedReader의 constructor 중 BufferedReader(Reader in)로 FileReader 인스턴스를 받았다.
package practice.io;
import java.io.*;
public class WriterClass {
private PrintWriter pw = null;
private String path = null;
public WriterClass(String path) {
this.path = path;
}
public void write(String text) throws IOException {
System.out.println(" -- write() START -- ");
System.out.println("text: " + text);
pw = new PrintWriter(path); // 기존 파일에 내용을 덧붙이려면 new PrintWriter(new FileWriter(path, true));
pw.println(text + "\r\nCopied.");
pw.close();
System.out.println(" -- write() END -- ");
}
}
java.io.Writer
─PrintWriter
└OutputStreamWriter
─FileWriter
PrintWriter의 constructor 중 PrintWriter(String fileName)으로 파일경로를 받아 인스턴스를 생성했다.
수정모드: PrintWriter(Writer out)으로 FileWriter 인스턴스를 받았다.
- new PrintWriter(new FileWriter(path), true);
이렇게 PrintWriter(Writer out, boolean autoFlush)로 하면 수정하지 않고 덮어쓴다. 왜 그럴까?