[Java] 콘솔 & 파일 입출력

·2022년 10월 16일

JAVA

목록 보기
6/10

콘솔 입출력


System.out.println("내용");

콘솔 출력을 위해 사용해 온 위 메서드는 PrintStream 클래스의 메서드다.
println은 콘솔에 문자열을 출력하고 ln, 즉 줄바꿈을 수행해 준다.
한편 System.out.printf를 사용하면 C에서 사용했던 printf처럼, %d, %s 등을 사용한 서식과 변수를 따로 전달해 출력할 수 있다.
System.err.println을 사용하면 오류 메세지 출력이 가능하다.

 

그렇다면 콘솔에서의 입력은 어떻게 받을 수 있을까?

InputStream

import java.io.IOException;
import java.io.InputStream;

public class Example {
    public static void main(String[] args) throws IOException {
        InputStream is = System.in;
        int a;
        a = is.read();
        System.out.println(a);
    }
}

InputStream의 read 메서드는 1 byte의 입력을 받아들인다. 한편 사용자의 입력은 우선 문자로 처리되기 때문에 0을 입력해도 숫자 0이 아닌 0의 아스키코드값(48)이 int a에 저장된다.
1 byte씩만 read되므로 그 이상을 저장하고 싶을 경우 여러 개의 변수에 나눠 저장하거나 byte 배열을 이용해야 한다.

InputStreamReader

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class Example {
    public static void main(String[] args) throws IOException {
        InputStream is = System.in;
        InputStreamReader inputStreamReader = new InputStreamReader(is);
        char[] a = new char[3];
        inputStreamReader.read(a);
        System.out.println(a);
    }
}

InputStreamReader를 이용하면 byte 단위로 아스키 코드값을 읽어오는 대신, char로 읽어와 바로 문자로 저장하고 출력할 수 있게 된다.

BufferedReader

import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

public class Example {
    public static void main(String[] args) throws IOException {
        InputStream is = System.in;
        InputStreamReader inputStreamReader = new InputStreamReader(is);
        BufferedReader buffReader = new BufferedReader(inputStreamReader);

        String a = buffReader.readLine();
        System.out.println(a);
    }
}

BufferedReader를 이용하면 이제 배열 대신 바로 문자열로 저장할 수 있게 된다.
readLine 메서드는 사용자가 엔터키를 입력할 때까지 입력을 받다가, 엔터가 입력되면 스트림을 닫고 문자열을 저장한다.

Scanner

하지만 여러분은 아마도 그간 콘솔 입력을 받을 때 Scanner을 이용해 왔을 것이다.
위에서 살펴본 메서드들은 불편한 점이 남아있을 뿐더러 객체를 만들고 감싸고 감싸니 불편하게 느껴진다.
J2SE 5.0부터 추가된 Scanner 클래스를 이용해 편하게 입력을 받아보자.

import java.util.Scanner;

public class Example {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println(scanner.next());
    }
}

Scanner 역시 콘솔입력 InputStream을 System.in으로 받아 생성되는 것이 이제는 눈에 보인다.
Scanner 객체의 next() 메서드는 단어 하나를 받아들인다. nextLine은 한 줄을, nextInt는 정수를 받아들이는 등 여러 간편한 메서드들이 있어 필요에 따라 사용할 수 있다.

 

 

파일 입출력


파일 출력은 즉 파일의 작성이다. Java에서 파일 출력을 수행해 보자.

파일 출력

파일 작성

import java.io.FileOutputStream;
import java.io.IOException;

public class Example {
    public static void main(String[] args) throws IOException {
        FileOutputStream output = new FileOutputStream("c:/out.txt");
        String data = "Hello java!\r\nWe made a file!\r\n";
        output.write(data.getBytes());
        output.close();
    }
}

c:/out.txt 파일이 생성된 것을 볼 수 있다. 지정된 경로에 아웃풋 스트림을 열고 데이터를 작성한다.
FileOutputStream도 byte 단위로 데이터를 처리하기 때문에 String을 getBytes()로 byte 배열로 바꿔 전달한다.
하지만 FileWriter 클래스를 이용해 FileWriter fileWriter = new FileWriter("c:/out.txt"); 파일을 열고, fileWriter.write(data);로 사용하면 byte 대신 문자열을 바로 출력할 수 있다.
하지만 줄바꿈을 위해 \r\n을 덧붙여야 한다니, 명색이 java인데 너무 귀찮게 느껴지지 않는가?
PrintWriter 클래스를 이용하면 println을 파일에서도 이용할 수 있다.

import java.io.IOException;
import java.io.PrintWriter;

public class Example {
    public static void main(String[] args) throws IOException {
        PrintWriter pw = new PrintWriter("c:/out.txt");
        String str1 = "Hello java!";
        String str2 = "We made a file!";
        pw.println(str1);
        pw.println(str2);
        pw.close();
    }
}

파일 내용 추가 작성

매번 파일을 생성하거나 완전히 덮어써버릴 순 없다. 파일에 내용을 추가하기 위해선 어떻게 해야 할까?

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class Example {
    public static void main(String[] args) throws IOException {
        PrintWriter pw = new PrintWriter("c:/out.txt");
        String str2 = "Hello java!";
        pw.println(str1);
        pw.close();


        PrintWriter pw2 = new PrintWriter(new FileWriter("c:/out.txt", true));
        String str2 = "We made a file!";
        pw2.println(str2);
        pw2.close();
    }
}

파일의 아웃풋스트림을 열 때 true를 같이 전달하는 것을 볼 수 있다. 이는 추가모드로 열 것인지에 대한 boolean 파라미터를 전달하는 것으로, true로 넣을 경우 추가모드로 파일을 수정할 수 있게 된다.

 

 

파일 읽기

콘솔 때와 유사하게 FileInputStream을 사용하면 바이트 단위로 파일을 읽어올 수 있지만, 대신 라인 단위로 읽어올 수 있는 BufferedReader을 사용해 보자.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class Example {
    public static void main(String[] args) throws IOException {
        BufferedReader buffReader = new BufferedReader(new FileReader("c:/out.txt"));
        while(true) {
            String line = buffReader.readLine();
            if (line==null) break;
            System.out.println(line);
        }
        buffReader.close();
    }
}

라인 단위로 파일을 읽을 수 있고 더 이상 라인이 없을 경우(null) 종료한다.

 

Java는 프로그램 종료 시 사용한 파일 스트림을 알아서 닫지만 사용했던 파일을 닫지 않고 다시 사용하려고 하면 에러가 발생하므로 반! 드! 시! 닫도록 한다.

 

 


이 글은 점프 투 자바를 읽고 스터디한 글입니다.

0개의 댓글