이전 포스팅에서 쓰기를 해봤으니 읽기를 해보려고 한다.
import java.io.FileInputStream;
import java.io.IOException;
public class FileRead {
public static void main(String[] args) throws IOException {
byte[] b = new byte[1024];
FileInputStream input = new FileInputStream("c:/out.txt");
input.read(b);
System.out.println(new String(b));
input.close();
}
}
1024byte 단위로 읽어오게 되는데, InputStream에 b를 저장했다가 출력하는 방식이다.
다만 정확한 길이를 모를 경우에는 불편한 방법이다.
라인단위로 읽기 위해서는 BufferedReader를 사용하면 된다.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class FileRead {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("c:/out.txt"));
while(true) {
String line = br.readLine();
if (line==null) break;
System.out.println(line);
}
br.close();
}
}
BufferedReaer를 이용해서 파일을 불러오고 한 줄씩 읽어서 print 하는 방식이다.
아마 이 방식을 더 많이 사용하지 않을까?
'Back-End > Java' 카테고리의 다른 글
File I/O : FileWriter 로 내용 추가하기 (0) | 2021.04.02 |
---|---|
File I/O : FileWriter, PrintWriter (0) | 2021.04.02 |
File I/O : FileOutputStream (0) | 2021.04.01 |
댓글