[JAVA] 입출력

XXXX·2024년 1월 10일
0
post-thumbnail

콘솔 입력

  • 입출력 방식 중 콘솔 입력 방법
System.in.read()
InputStreamReader reader = ...
BufferedReader br = ..
Scanner ... // 제일 많이 사용!

콘솔 출력

  • 입출력 방식 중 콘솔 출력 방법
System.our.println(...); // 엔터키 포함 출력
System.out.print(...);
System.our.printf(...); // 포맷 지정해서 출력

// Java 프로그래밍 - 입출력_1

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

public class Main {

    public static void referInputStream() throws IOException {
//      System.in
        System.out.println("== System.in ==");
        System.out.print("입력 :");
        int a = System.in.read() - '0'; // char 값 하나를 받아오고, 숫자로 변환
        System.out.println("a = " + a);
        System.in.read(new byte[System.in.available()]);
        // 입력 스트림에 남아 있는 개수만큼 바이트 형태로 읽어서 데이터를 소진 시켜준다.


//      InputStreamReader
        System.out.println("== InputStreamReader ==");
        InputStreamReader reader = new InputStreamReader(System.in);
        char[] c = new char[3]; // 3개의 데이터 받음
        System.out.print("입력: ");
        reader.read(c);
        System.out.println(c);


//      BufferedReader
        System.out.println("== BufferedReader ==");
        // 원하는 개수만큼 자유자제로 읽어들일 수가 있다
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("입력: ");
        String s1 = br.readLine();
        System.out.println("s1 = " + s1);

    }
    

// 	제일 많이 사용되는 방식 !
    public static void main(String[] args) throws IOException {

//      1. 입력
//      1-1. 다른 입력 방식 참고
        referInputStream();

//      1-2. Scanner
        System.out.println("== Scanner ==");
        Scanner sc = new Scanner(System.in);
        System.out.print("입력1: ");
        System.out.println(sc.next()); - 데이터 하나 받아오기
//        sc.nextLine(); - 엔터키 소진

        System.out.print("입력2: ");
        System.out.println(sc.nextInt()); //int 값만 입력 가능
        sc.nextLine();

        System.out.print("입력3: ");
        System.out.println(sc.nextLine());



//      참고) 정수, 문자열 변환
        int num = Integer.parseInt("12345"); // 정수형으로 타입 변환
        String str = Integer.toString(12345) // String으로 타입 변환

        
//      2. 출력
        System.out.println("== 출력 ==");
        System.out.println("Hello");
        System.out.println("World!");

        System.out.print("Hello ");
        System.out.print("World!");
        System.out.println();

        System.out.printf("Hello ");
        System.out.printf("World!");
        System.out.println();

        String s = "자바";
        int number = 3;

        System.out.println(s + "는 언어 선호도 " + number + "위 입니다.");
        System.out.printf("%s는 언어 선호도 %d위 입니다.\n", s, number);

        System.out.printf("%d\n", 10);
        System.out.printf("%o\n", 10); // 8진수
        System.out.printf("%x\n", 10); // 16진수

        System.out.printf("%f\n", 5.2f);
        System.out.printf("%c\n", 'A');
        System.out.printf("%s\n", "안녕하세요");

        System.out.printf("%-5d\n", 123); // 5칸 자리를 마련 후 왼쪽에 맞춰 출력
        System.out.printf("%5d\n", 1234); // 5칸 자리를 마련 후 오른쪽에 맞춰 출력
        System.out.printf("%5d\n", 12345);

        System.out.printf("%.2f\n", 1.12645123f); // 소수점 둘째짜리까지 반올림하여 출력



    }
}

파일 출력

  • 입출력 방식 중 파일로 출력하는 방법
FileOutputStream ...
FileWriter ...
PrintWriter ...

파일 입력

  • 입출력 방식 중 파일로부터 입력 받는 방법
FileInputStream ...
BufferedReader ...

// Java 프로그래밍 - 입출력_2

import java.io.*;

public class Main {

    public static void main(String[] args) throws IOException {
//      1. 파일 쓰기
//      FileWriter
        FileWriter fw = new FileWriter("./memo.txt");
        String memo = "헤드 라인\n";
        fw.write(memo);

        memo = "1월 1일 날씨 맑음\n";

        fw.close();
        

//      PrintWriter
        PrintWriter pw = new PrintWriter("./memo.txt");
        memo = "헤드 라인";
        pw.println(memo);

        memo = "1월 1일 날씨 맑음";
        pw.println(memo);

        pw.close();
        

//      파일 이어 쓰기
        FileWriter fw2 = new FileWriter("./memo.txt", true);
        //append: true가 이어쓰는 걸 허용한다는 뜻!

        memo = "1월 2일 날씨 완전 맑음\n";
        fw2.write(memo);
        fw2.close();

        PrintWriter pw2 = new PrintWriter(new FileWriter("./memo.txt", true));

        memo = "1월 3일 날씨 또 맑음!";
        pw2.println(memo);
        pw.close();

//      2. 파일 입력
        BufferedReader br = new BufferedReader(new FileReader("./memo.txt"));

        while (true) {
            String line = br.readLine();

            if (line = null) {
                break;
            }

            System.out.println(line);

        }
        br.close();

    }
}

// Practice
// JamesArthurGosling.txt 파일을 읽은 후 원하는 단어 변경하여 새로 저장해보자.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class Practice {
    public static void main(String[] args) throws IOException {
        String inputFile = "./JamesArthurGosling.txt";
        String outputFile = "./JamesArthurGosling_edit.txt";

        // 찾을 단어 / 변경 단어 입력 받기
        System.out.print("찾을 단어: ");
        Scanner sc = new Scanner(System.in);
        String find = sc.nextLine();
        System.out.println("변경 단어: ");
        String to = sc.nextLine();


        // 파일 읽기, 변경 및 저장
        BufferedReader br = new BufferedReader(new FileReader(inputFile));
        FileWriter fw = new FileWriter(outputFile);

        while (true) {
            String line = br.readLine();
            if (line == null) {
                break;
            }

            String newLine = line.replace(fine, to);
            fw.write(newLine + '\n');
        }

        br.close();
        fw.close();

    }
}

0개의 댓글