콘솔 입출력, 파일 입출력

김민영·2023년 1월 23일
0

Java

목록 보기
10/14

콘솔 입출력

콘솔 입력

InputStream

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

public class test {

    public static void main(String[] args) throws IOException {

        InputStream in = System.in;
        
        int a;
        a = in.read();

        System.out.println(a);
    }
}
  • InputStream의 read 메소드는 1byte의 입력을 받음.
  • int 자료형으로 입력을 저장하면 0~255 사이의 아스키 코드 값이다.

IOException

  • throws IOException : InputStream으로 값을 읽을 때 발생할 수 있는 예외인 IOException을 throws를 사용하여 뒤로 미룸

Stream

  • 데이터의 흐름
  • ex. 키보드 입력 시 문자열, 파일 데이터 (시작~끝), HTTP 송수신 데이터

한 글자씩 입력받기

  • int 여러 개를 입력 받음.
import java.io.IOException;
import java.io.InputStream;

public class test {

    public static void main(String[] args) throws IOException {

        InputStream in = System.in;

        int a;
        int b;
        int c;

        a = in.read();
        b = in.read();
        c = in.read();

        System.out.println(a);
        System.out.println(b);
        System.out.println(c);
    }
}

한 번에 입력 받기

  • 배열로 입력 받음
import java.io.IOException;
import java.io.InputStream;

public class test {

    public static void main(String[] args) throws IOException {

        InputStream in = System.in;

        byte[] a = new byte[3];
        in.read(a);


        System.out.println(a[0]);
        System.out.println(a[1]);
        System.out.println(a[2]);
    }
}

InputStreamReader

  • 바이트 대신 문자로 입력 스트림 읽기 위해 InputStreamReader 사용
  • InputStreamReader 생성자에 InputStream 객체 넣음
  • 정해진 길이의 문자열을 입력 받음.
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class test {

    public static void main(String[] args) throws IOException {

        InputStream in = System.in;
        InputStreamReader reader = new InputStreamReader(in);
        
        char[] a = new char[3];
        reader.read(a);

        System.out.println(a);
    }
}

BufferedReader

  • 길이 정함 없이 사용자의 입력 전부를 받음
  • BufferedReader의 생성자로 InputStreamReader을 넣는다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class test {

    public static void main(String[] args) throws IOException {

        InputStream in = System.in;
        InputStreamReader reader = new InputStreamReader(in);
        BufferedReader br = new BufferedReader(reader);

        String a = br.readLine();

        System.out.println(a);
    }
}

InputStream 요약

  • InputStream - byte
  • InputStreamReader - character (생성시 InputStream 객체 필요)
  • BufferedReader - String (생성시 InputStreamReader 객체 필요)

Sacnner

  • 입력 쉽게 받기
import java.io.IOException;
import java.util.*;

public class test {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        System.out.println(sc.next());
    }
}
  • next() : 단어 하나
  • nextLine() : 한 줄
  • nextInt() : 정수

콘솔 출력

  • System.out.println
  • System.out : PrintStream 클래스의 객체
  • System.err : 오류메시지를 출력할 경우에 사용

파일 입출력

파일 쓰기

FileOutputStream

  • 파일 경로를 FileOutputStream 의 생성자에 입력하면 해당 파일이 생긴다.
  • FileOutputStream의 메소드 write를 통해 파일에 값을 입력한다.
  • String.getBytes()을 통해 문자열을 byte 배열로 바꿔야한다.
  • \r\n : 줄바꿈 문자
import java.io.*;

public class test {

    public static void main(String[] args) throws IOException {

        FileOutputStream output = new FileOutputStream("C:/Users/minyoung/Desktop/study/Java/untitled/out.txt");
        
        for (int i=0; i<11; i++) {
            String data = i + "번째 줄입니다.\r\n";
            output.write(data.getBytes());
        }
        
        output.close();
    }    
}

FileWriter

  • 문자열의 byte배열로 변환하지 않는 방식
  • FileWriter 객체를 사용하면 write 메소드에 문자열을 입력해도 된다.
import java.io.*;

public class test {

    public static void main(String[] args) throws IOException {

        FileWriter fw = new FileWriter("C:/Users/minyoung/Desktop/study/Java/untitled/out.txt");

        for (int i=0; i<11; i++) {
            String data = i + "번째 줄입니다.\r\n";
            fw.write(data);
        }

        fw.close();
    }    
}

PrintWriter

  • \r\n 없이 줄바꿈 하기
  • PrintWriter의 println 메소드를 사용한다.
  • 콘솔 출력의 System.out.println과 비슷한 형식이다.
import java.io.*;

public class test {

    public static void main(String[] args) throws IOException {

        PrintWriter pw = new PrintWriter("C:/Users/minyoung/Desktop/study/Java/untitled/out.txt");

        for (int i=0; i<11; i++) {
            String data = i + "번째 줄입니다.\r\n";
            pw.println(data);
        }

        pw.close();
    }    
}

파일에 내용 추가

FileWriter 사용

  • 내용을 추가하기 위한 FileWriter에는 두 번째 매개변수를 True로 지정하고 생성한다.
import java.io.*;

public class test {

    public static void main(String[] args) throws IOException {

        FileWriter fw = new FileWriter("C:/Users/minyoung/Desktop/study/Java/untitled/out.txt");

        for (int i=0; i<11; i++) {
            String data = i + "번째 줄입니다.\r\n";
            fw.write(data);
        }

        fw.close();
        
        FileWriter fw2 = new FileWriter("C:/Users/minyoung/Desktop/study/Java/untitled/out.txt", True);

        for (int i=11; i<21; i++) {
            String data = i + "번째 줄입니다.\r\n";
            fw2.write(data);
        }

        fw2.close();
    }    
}

PrintWriter 사용

  • 새로 추가하려는 PrintWriter 객체를 생성할 때, 추가 모드의 FileWriter 객체를 전달해야 한다.
import java.io.*;

public class test {

    public static void main(String[] args) throws IOException {

        PrintWriter pw = new PrintWriter("C:/Users/minyoung/Desktop/study/Java/untitled/out.txt");

        for (int i=0; i<11; i++) {
            String data = i + "번째 줄입니다.";
            pw.println(data);
        }

        pw.close();

        PrintWriter pw2 = new PrintWriter(new FileWriter("C:/Users/minyoung/Desktop/study/Java/untitled/out.txt", true));

        for (int i = 11; i<21;i++) {
            String data = i+"번째 줄입니다.";
            pw2.println(data);
        }

        pw2.close();

    }    
}

파일 읽기

FileInputStream

  • FileInputStream 객체의 read 메소드를 사용한다.
  • byte코드로 읽어들인 내용을 String으로 바꿔서 출력한다.
import java.io.*;

public class test {

    public static void main(String[] args) throws IOException {

        byte[] b = new byte[1024];
        FileInputStream input = new FileInputStream("C:/Users/minyoung/Desktop/study/Java/untitled/out.txt");
        input.read(b);
        System.out.println(new String(b));
        input.close();

    }    
}

BufferedReader

  • 라인 단위로 문자열 읽기
  • BufferedReader 객체를 생성할 때는 FileReader 객체를 생성자에 넣어준다.
import java.io.*;

public class test {

    public static void main(String[] args) throws IOException {

        BufferedReader br = new BufferedReader(new FileReader("C:/Users/minyoung/Desktop/study/Java/untitled/out.txt"));
        while(true) {
            String line = br.readLine();
            if (line==null) break;
            System.out.println(line);
        }
        br.close();

    }    
}
profile
노션에 1차 정리합니당 - https://cream-efraasia-f3c.notion.site/4fb02c0dc82e48358e67c61b7ce8ab36?v=

0개의 댓글