본문 바로가기
Java/정리

[Java] 파일 출력 방법들

by 콧등치기국수 2021. 12. 23.

이전 글 중 "[Java] IO(입출력)_스트림"은 자바에서 파일 입출력의 전반적인 내용을 다뤘었다.

이번 글에서는 자바에서 파일을 이용한 출력방법들과 각 방법들의 차이점에 대해 알아보려한다.

 

파일 쓰기

FileOutputStream
public class FileOut {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		opStream("fileOutputStream.txt");
		fWriter("fileWriter.txt");
		pWriter("printWriter.txt");		
	}

	static void opStream(String fileName) {
		try {
			FileOutputStream output = new FileOutputStream(fileName);
			
			for(int i=1; i<=20; i++) {
				String content = i + "번째 줄입니다.\r\n";
				output.write(content.getBytes());
			}
			
			output.close();
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

1. 바이트 단위로 데이터를 처리하는 클래스이다.

2. FileOutputStream에 값을 쓸 때는 byte 배열로 써야하므로 String을 byte[]로 변경해줘야 한다.

- getBytes() 메소드를 이용하면 된다.

- "\r\n"은 줄바꿈 문자이다.

 

FileWriter
public class FileOut {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		opStream("fileOutputStream.txt");
		fWriter("fileWriter.txt");
		pWriter("printWriter.txt");
		
	}
    
	static void fWriter(String fileName) {
		try {
			FileWriter fw = new FileWriter(fileName);
			
			for(int i=1; i<=20; i++) {
				String content = i + "번째 줄입니다.\r\n";
				fw.write(content);
			}
			
			fw.close();
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

1. 문자 단위로 데이터를 처리하는 클래스이다. 

2. String을 byte[]로 변경하지 않고 문자열을 바로 file에 출력할 수 있다. 따라서 문자열을 파일에 쓸 때에 FileOutputStream보다 편리하게 쓸 수 있다.

- "\r\n"은 줄바꿈 문자이다.

 

PrintWriter
public class FileOut {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		opStream("fileOutputStream.txt");
		fWriter("fileWriter.txt");
		pWriter("printWriter.txt");
		
	}
    
	static void pWriter(String fileName) {
		try {
			PrintWriter pw = new PrintWriter(fileName);
			
			for(int i=1; i<=20; i++) {
				String content = i + "번째 줄입니다.";
				pw.println(content);
			}
			
			pw.close();
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

 

1. 문자 단위로 데이터를 처리하는 클래스이다.

2. String을 byte[]로 변경하지 않아도 되고, "\r\n"으로 줄바꿈을 하지 않아도 된다.

- PrintWriter객체.println(문자열)  =>"\r\n"없이 줄바꿈을 할 수 있다.

3. File(String), OutputStream, Writer 등의 객체를 인수로 받아 더 간편하게 스트림을 연결할 수 있다.

 

결과

3가지 방법 모두 결과는 아래와 같이 같게 나온다.

 

 

참고

1. https://wikidocs.net/227

2. https://dream-space.tistory.com/4

3. https://hianna.tistory.com/587

 

파일 입력도 다음에 알아보면 좋을 것 같다.