이 글에서는 Java를 사용해 파일에 데이터를 쓰는 다섯 가지 방법을 예제 코드와 함께 살펴봅니다. 모든 코드는 파일 쓰기 전에 해당 파일이 존재하는지 먼저 확인하고, 파일이 없으면 새로 생성하도록 작성되어 있습니다.
BufferedWriter를 사용한 파일 쓰기
BufferedWriter는 내부 버퍼를 활용해 입출력 성능을 높이는 대표적인 방식입니다. 텍스트 데이터를 효율적으로 파일에 기록할 때 가장 널리 사용됩니다.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class WriteToFile {
public static void main( String[] args ) {
try {
String content = "파일에 쓸 내용";
// 파일 이름과 경로
File file = new File("writefile.txt");
if(!file.exists()){
file.createNewFile();
}
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
} catch(IOException ex) {
System.out.println("예외가 발생했습니다:");
ex.printStackTrace();
}
}
}
참고: 기존 파일을 덮어쓰지 않고 내용을 이어서 추가(append)하려면 FileWriter 객체를 생성할 때 두 번째 인자로 true를 전달하면 됩니다.
FileWriter fw = new FileWriter(file, true);
관련 글
- Java에서 파일 생성하는 방법
- Java에서 현재 작업 디렉터리 확인하는 방법
PrintWriter를 사용한 파일 쓰기
PrintWriter는 println(), printf()처럼 편리한 출력 메서드를 제공하므로, 형식화된 텍스트를 파일에 쓸 때 유용합니다.
import java.io.*;
public class WriteToFile {
public static void main( String[] args ) {
try {
String content = "파일에 쓸 내용";
// 파일 이름과 경로
File file = new File("writefile.txt");
if(!file.exists()){
file.createNewFile();
}
FileWriter fw = new FileWriter(file);
PrintWriter bw = new PrintWriter(fw);
bw.write(content);
bw.close();
} catch(IOException ex) {
System.out.println("예외가 발생했습니다:");
ex.printStackTrace();
}
}
}
FileOutputStream을 사용한 파일 쓰기
FileOutputStream은 바이트 단위로 데이터를 기록하는 스트림입니다. 문자열을 바이트 배열로 변환해 쓰기 때문에 이미지 등 바이너리 데이터 처리에도 적합합니다.
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class WriteToFile {
public static void main( String[] args ) {
try {
String content = "파일에 쓸 내용";
// 파일 이름과 경로
File file = new File("writefile.txt");
if(!file.exists()){
file.createNewFile();
}
FileOutputStream outStream = new FileOutputStream(file);
byte[] strToBytes = content.getBytes();
outStream.write(strToBytes);
outStream.close();
} catch(IOException ex) {
System.out.println("예외가 발생했습니다:");
ex.printStackTrace();
}
}
}
Files 클래스를 사용한 파일 쓰기
Java 7부터 도입된 NIO의 Files 클래스를 사용하면 한 줄의 코드만으로 간단하게 파일을 쓸 수 있습니다. 짧은 텍스트 파일을 다룰 때 가장 깔끔한 방법입니다.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class WriteToFile {
public static void main( String[] args ) {
Path path = Paths.get("writefile.txt");
String content = "파일에 쓸 내용";
try {
byte[] bytes = content.getBytes();
Files.write(path, bytes);
} catch(IOException ex) {
System.out.println("예외가 발생했습니다:");
ex.printStackTrace();
}
}
}
DataOutputStream을 사용한 파일 쓰기
DataOutputStream은 자바의 기본형 데이터(primitive type)를 그대로 파일에 기록할 수 있게 해줍니다. writeUTF() 메서드를 사용하면 UTF-8 형식의 문자열도 손쉽게 저장할 수 있습니다.
import java.io.*;
public class WriteToFile {
public static void main( String[] args ) {
String content = "파일에 쓸 내용";
try {
File file = new File("writefile.txt");
if(!file.exists()){
file.createNewFile();
}
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
DataOutputStream dataOutStream = new DataOutputStream(bos);
dataOutStream.writeUTF(content);
dataOutStream.close();
} catch(IOException ex) {
System.out.println("예외가 발생했습니다:");
ex.printStackTrace();
}
}
}
이상으로 Java에서 파일에 쓰는 다섯 가지 방법을 살펴보았습니다. 상황과 데이터 유형에 따라 적절한 방식을 선택하면 되며, 일반적인 텍스트 파일에는 BufferedWriter나 Files 클래스가 가장 많이 활용됩니다.