자바의 java.io 패키지는 입출력(IO)을 처리하는데 필수적인 클래스들을 제공합니다. 이 패키지는 데이터의 입출력 처리와 관련된 다양한 스트림 클래스를 포함하고 있어, 프로그램이 파일, 네트워크, 메모리 등에서 데이터를 읽고 쓰는 작업을 간단하게 처리할 수 있게 도와줍니다.
방향에 따른 구분
데이터 종류에 따른 구분
public class ByteStreamExample {
public void readBytes() throws IOException {
FileInputStream fis = new FileInputStream("test.dat");
try {
int data;
while ((data = fis.read()) != -1) {
// 바이트 데이터 처리
}
} finally {
fis.close();
}
}
}
public class ByteOutputExample {
public void writeBytes() throws IOException {
FileOutputStream fos = new FileOutputStream("test.dat");
try {
String data = "Hello, World!";
fos.write(data.getBytes());
} finally {
fos.close();
}
}
}
public class ReaderExample {
public void readChars() throws IOException {
FileReader reader = new FileReader("test.txt");
try {
int character;
while ((character = reader.read()) != -1) {
// 문자 데이터 처리
System.out.print((char) character);
}
} finally {
reader.close();
}
}
}
public class WriterExample {
public void writeChars() throws IOException {
FileWriter writer = new FileWriter("test.txt");
try {
String text = "안녕하세요!";
writer.write(text);
} finally {
writer.close();
}
}
}
public class BufferedStreamExample {
public void copyFile() throws IOException {
try (BufferedInputStream bis = new BufferedInputStream(
new FileInputStream("source.file"));
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream("target.file"))) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = bis.read(buffer)) != -1) {
bos.write(buffer, 0, bytesRead);
}
}
}
}
public class BufferedReaderWriterExample {
public void processLines() throws IOException {
try (BufferedReader reader = new BufferedReader(
new FileReader("input.txt"));
BufferedWriter writer = new BufferedWriter(
new FileWriter("output.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine();
}
}
}
}
public class DataStreamExample {
public void writeData() throws IOException {
try (DataOutputStream dos = new DataOutputStream(
new FileOutputStream("data.bin"))) {
dos.writeInt(123);
dos.writeDouble(3.14);
dos.writeUTF("Hello");
}
}
public void readData() throws IOException {
try (DataInputStream dis = new DataInputStream(
new FileInputStream("data.bin"))) {
int number = dis.readInt();
double value = dis.readDouble();
String text = dis.readUTF();
}
}
}
public class SerializationExample {
public void serialize() throws IOException {
try (ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream("object.ser"))) {
MyClass obj = new MyClass();
oos.writeObject(obj);
}
}
public void deserialize() throws IOException, ClassNotFoundException {
try (ObjectInputStream ois = new ObjectInputStream(
new FileInputStream("object.ser"))) {
MyClass obj = (MyClass) ois.readObject();
}
}
}
public class FileExample {
public void fileOperations() {
File file = new File("example.txt");
// 파일 정보 확인
System.out.println("존재 여부: " + file.exists());
System.out.println("파일 크기: " + file.length());
System.out.println("읽기 가능: " + file.canRead());
System.out.println("쓰기 가능: " + file.canWrite());
// 디렉토리 생성
File dir = new File("newDir");
dir.mkdir();
// 파일 목록 조회
File[] files = dir.listFiles();
}
}
public class RandomAccessFileExample {
public void randomAccess() throws IOException {
try (RandomAccessFile file = new RandomAccessFile("random.dat", "rw")) {
// 파일 포인터 이동
file.seek(1000);
// 데이터 쓰기
file.writeInt(123);
// 파일 포인터 처음으로 이동
file.seek(0);
// 데이터 읽기
int value = file.readInt();
}
}
}
public class StreamChainingExample {
public void chainedStream() throws IOException {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(
new FileInputStream("input.txt"), "UTF-8"))) {
String line;
while ((line = reader.readLine()) != null) {
// 처리 로직
}
}
}
}
Java의 I/O 패키지에 대해 자세히 정리해드리겠습니다.
방향에 따른 구분
데이터 종류에 따른 구분
public class ByteStreamExample {
public void readBytes() throws IOException {
FileInputStream fis = new FileInputStream("test.dat");
try {
int data;
while ((data = fis.read()) != -1) {
// 바이트 데이터 처리
}
} finally {
fis.close();
}
}
}
public class ByteOutputExample {
public void writeBytes() throws IOException {
FileOutputStream fos = new FileOutputStream("test.dat");
try {
String data = "Hello, World!";
fos.write(data.getBytes());
} finally {
fos.close();
}
}
}
public class ReaderExample {
public void readChars() throws IOException {
FileReader reader = new FileReader("test.txt");
try {
int character;
while ((character = reader.read()) != -1) {
// 문자 데이터 처리
System.out.print((char) character);
}
} finally {
reader.close();
}
}
}
public class WriterExample {
public void writeChars() throws IOException {
FileWriter writer = new FileWriter("test.txt");
try {
String text = "안녕하세요!";
writer.write(text);
} finally {
writer.close();
}
}
}
public class BufferedStreamExample {
public void copyFile() throws IOException {
try (BufferedInputStream bis = new BufferedInputStream(
new FileInputStream("source.file"));
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream("target.file"))) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = bis.read(buffer)) != -1) {
bos.write(buffer, 0, bytesRead);
}
}
}
}
public class BufferedReaderWriterExample {
public void processLines() throws IOException {
try (BufferedReader reader = new BufferedReader(
new FileReader("input.txt"));
BufferedWriter writer = new BufferedWriter(
new FileWriter("output.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine();
}
}
}
}
public class DataStreamExample {
public void writeData() throws IOException {
try (DataOutputStream dos = new DataOutputStream(
new FileOutputStream("data.bin"))) {
dos.writeInt(123);
dos.writeDouble(3.14);
dos.writeUTF("Hello");
}
}
public void readData() throws IOException {
try (DataInputStream dis = new DataInputStream(
new FileInputStream("data.bin"))) {
int number = dis.readInt();
double value = dis.readDouble();
String text = dis.readUTF();
}
}
}
public class SerializationExample {
public void serialize() throws IOException {
try (ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream("object.ser"))) {
MyClass obj = new MyClass();
oos.writeObject(obj);
}
}
public void deserialize() throws IOException, ClassNotFoundException {
try (ObjectInputStream ois = new ObjectInputStream(
new FileInputStream("object.ser"))) {
MyClass obj = (MyClass) ois.readObject();
}
}
}
public class FileExample {
public void fileOperations() {
File file = new File("example.txt");
// 파일 정보 확인
System.out.println("존재 여부: " + file.exists());
System.out.println("파일 크기: " + file.length());
System.out.println("읽기 가능: " + file.canRead());
System.out.println("쓰기 가능: " + file.canWrite());
// 디렉토리 생성
File dir = new File("newDir");
dir.mkdir();
// 파일 목록 조회
File[] files = dir.listFiles();
}
}
public class RandomAccessFileExample {
public void randomAccess() throws IOException {
try (RandomAccessFile file = new RandomAccessFile("random.dat", "rw")) {
// 파일 포인터 이동
file.seek(1000);
// 데이터 쓰기
file.writeInt(123);
// 파일 포인터 처음으로 이동
file.seek(0);
// 데이터 읽기
int value = file.readInt();
}
}
}
public class StreamChainingExample {
public void chainedStream() throws IOException {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(
new FileInputStream("input.txt"), "UTF-8"))) {
String line;
while ((line = reader.readLine()) != null) {
// 처리 로직
}
}
}
}
이러한 Java I/O 패키지의 주요 특징 및 사용시 고려사항은 다음과 같습니다:
성능 고려사항:
에러 처리:
인코딩 고려:
보안 고려사항:
실무에서 자주 사용되는 패턴: