본문으로 건너뛰기
Advertisement

표준 I/O와 File 클래스

1. 표준 입출력 (Standard I/O)

자바는 콘솔 화면에서 사용자로부터 입력을 받거나 텍스트를 출력하기 위해 미리 만들어진(Built-in) 표준 스트림 3가지를 System 클래스 내에 static 변수로 제공합니다.

  • System.in: 콘솔로부터 데이터를 입력받는 바이트 기반 입력 스트림 (InputStream)
  • System.out: 콘솔로 데이터를 출력하는 바이트 기반 출력 스트림 (PrintStream)
  • System.err: 에러 메시지를 출력하기 위한 스트림 (일반적으로 붉은색 글씨로 콘솔에 나타남)
import java.io.IOException;

public class StandardIOEx {
public static void main(String[] args) {
System.out.println("문자를 입력하세요 (종료(ctrl+z) 또는 ctrl+d): ");
System.err.println("이것은 에러 스트림을 통해 출력된 메시지입니다.");

try {
int input;
while ((input = System.in.read()) != -1) {
System.out.print((char) input);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

2. File 클래스

java.io.File 은 데이터 입출력을 위한 스트림이 아니라, 파일(File) 또는 디렉토리(Directory) 자체의 제어와 정보 를 다루는 클래스입니다. 파일의 크기, 쓰기 가능 여부를 묻거나 삭제/생성하는 작업을 할 때 사용합니다. 자바 7부터는 더 개선된 java.nio.file.FilesPath 사용을 권장하기도 하지만 여전히 널리 쓰입니다.

import java.io.File;
import java.io.IOException;

public class FileExample {
public static void main(String[] args) throws IOException {
File file = new File("C:\\example", "new_file.txt");
File dir = new File("C:\\example");

// 디렉토리가 없으면 생성
if (!dir.exists()) {
dir.mkdirs();
}

// 파일이 없으면 새 파일 생성
if (!file.exists()) {
boolean isCreated = file.createNewFile();
System.out.println("파일 생성 여부: " + isCreated);
}

System.out.println("파일명: " + file.getName());
System.out.println("절대 경로: " + file.getAbsolutePath());
System.out.println("크기: " + file.length() + " bytes");
}
}

파일 객체는 I/O 스트림(예: FileInputStream)의 생성자에 넘겨주어 해당 파일을 쉽게 읽거나 쓸 수 있도록 돕습니다.

Advertisement