수행할 내용:

1. 파일명 ?을 입력 받아서 파일을 생성하고

2. 회원 ?명의 이름을 입력받아 작성한다

3. 파일로부터 모든 회원을 읽어들여 String 배열에 저장하고, 출력하기

 

import java.io.*;
import java.util.Arrays;
import java.util.Scanner;

public class Work1 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        /*
            파일명을 입력 받아 작성하고
            파일에 회원 ?명을 입력받아 작성한다
            파일로부터 모든 회원을 읽어 들여 String 배열에 저장한다
         */

        // 파일명을 입력 받아 작성
        System.out.print("생성할 파일명 입력 >>> ");
        String user_input = sc.next();
        String fileDir = "e:\\" + user_input + ".txt";
        File newFile = new File(fileDir);

        // 파일에 회원 ?명을 입력받아 작성
        System.out.print("입력할 회원수 입력 >>> ");
        int user_input_num = sc.nextInt();

        for (int i=0; i<user_input_num; i++) {
            System.out.print("회원명 입력 >>> ");
            String st = sc.next();
            try {
                FileWriter fw = new FileWriter(newFile, true); // append 모드로 열기
                fw.write(st + "\n");
                fw.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        // 파일로부터 모든 회원을 읽어 들여 String 배열에 저장
        try {
            FileReader fr = new FileReader(newFile);
            BufferedReader br = new BufferedReader(fr);

            // 데이터 읽어오기
            String names = "";
            String str = "";

            while ((str = br.readLine()) != null){
                names = names + str + "-";
            }
            br.close();

            names = names.substring(0, names.length()-1);   // 맨 끝에 붙은 토큰 제거 => .substring(시작 인덱스, 끝 인덱스)

            String[] nameArr = names.split("-");

            System.out.println(names);
            System.out.println(Arrays.toString(nameArr));

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}

+ Recent posts