- new FileOutputStream("temp"/hello.dat")
- 파일에 데이터를 출력하는 스트림이다.
- 파일이 없으면 파일을 자동으로 만들고, 데이터를 해당 파일에 저장한다.
- 폴더를 만들지는 않기 때문에 폴더는 미리 만들어두어야 한다.
- write()
- byte 단위로 값을 출력한다.
- new FileInputStream("temp/hello.dat")
- 파일에서 데이터를 읽어오는 스트림이다.
- read()
- 파일에서 데이터를 byte 단위로 하나씩 읽어온다.
- 파일의 끝에 도달해서 더는 읽을 내용이 없다면 -1 을 반환한다. 파일의 끝(EOF, End of File)
부분으로 나누어 읽기
public static void main(String[] args) throws IOException {
FileOutputStream fos = new FileOutputStream("temp/hello.dat");
byte[] input = {65, 66, 67};
fos.write(input);
fos.close();
FileInputStream fis = new FileInputStream("temp/hello.dat");
byte[] buffer = new byte[10];
int readCount = fis.read(buffer, 0, 10);
System.out.println("readCount = " + readCount);
System.out.println(Arrays.toString(buffer));
fis.close();
}
- read(byte[], offset, length)
한번에 읽기
public static void main(String[] args) throws IOException {
FileOutputStream fos = new FileOutputStream("temp/hello.dat");
byte[] input = {65, 66, 67};
fos.write(input);
fos.close();
FileInputStream fis = new FileInputStream("temp/hello.dat");
byte[] readBytes = fis.readAllBytes();
System.out.println(Arrays.toString(readBytes));
fis.close();
}
-readAllBytes()
'개발이 좋아서 > Java가 좋아서' 카테고리의 다른 글
I/O 기본1 - 파일 입출력과 성능 최적화 (buffered) (0) | 2024.11.26 |
---|---|
I/O 기본1 - InputStream / OutputStream (0) | 2024.11.26 |
문자 인코딩 (0) | 2024.11.26 |
Exception (0) | 2023.05.09 |
내부 클래스 (0) | 2023.05.09 |