
파일 쓰기 작업을 하는 클래스 이다.
파일을 쓰기 위해 물리적 파일 경로를 지정할 때 반드시 해당 경로의 폴더는 존재해야 한다.
경로내에 폴더가 없으면 FileNotFoundException가 발생한다.
파일 쓰기 과정
1)FileOutputStream 객체 생성
2)쓰기 작업
write() 함수 반복 이용
byte[] 객체를 이용할수 있음
3)읽기 종료
쓰기(write())
package com.java.io04_fileoutputstream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class FileoutPutStream01 {
public static void main(String[] args) throws IOException {
// OutStream > FileOutPutStream : 쓰기(write())
// 1.파일 객체 생성
File outFile = new File("C:\\\\FileTest\\\\dir1\\\\test01.txt");
//2.출력스트림 생성
//덮어쓰기
OutputStream os01 = new FileOutputStream(outFile);
os01.write('c');
os01.write('a');
os01.write('f');
os01.write('e');
os01.write('\\r'); //캐리지 리턴(carriage return 13) 시작위치
os01.write('\\n'); //라인피드(line feed 10) 다음칸
//windows \\r + \\n (CR +LF)
//linux,mac \\n
os01.flush(); //메모리를 비운다. 출력--->HDD,NIC,...
os01.close();
//이어 쓰기
OutputStream os02 = new FileOutputStream(outFile,true);
//바이트 배열로 쓰기
byte [] buffer = "hello".getBytes();
os02.write(buffer);
os02.write('\\n');
os02.flush();
os02.close();
OutputStream os03 = new FileOutputStream(outFile,true);
byte[] buffer02 ="Better the last smile than the first lauter".getBytes();
os03.write(buffer02,7,8);
os03.flush();
os03.close();
}
}
한글 출력
package com.java.io04_fileoutputstream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
public class FileoutPutStream02 {
public static void main(String[] args) throws IOException {
// OutStream > FileOutPutStream : 쓰기
// 1.파일 객체 생성
File outFile = new File("C:\\\\FileTest\\\\dir1\\\\test01.txt");
//2.출력 스트림 생성
OutputStream os01 = new FileOutputStream(outFile);
byte [] buffer = "안녕하세요".getBytes(Charset.forName("UTF-8")); //1000111
os01.write(buffer);
os01.write('\\n');
os01.flush();
os01.close();
OutputStream os02 = new FileOutputStream(outFile,true);
byte [] buffer02 = "반갑습니다.".getBytes(Charset.forName("UTF-8"));
os02.write(buffer02,6,6);
os02.write('\\n');
os02.flush();
os02.close();
}
}