상세 컨텐츠

본문 제목

[입출력] 입력해서 어레이리스저장 출력 반쯤된거

자바

by esoesmio 2023. 4. 7. 21:42

본문

import javax.print.DocFlavor;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;

public class z21 {

    ArrayList<String> arr = new ArrayList<>();

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        z21 z= new z21();
        System.out.println("뭘 하시겠습니까?");

        System.out.println("1. 사람이름 입력하기");
        System.out.println("1. 사람이름 출력하기");

        System.out.println("세 사람 이름을 입력하시오");
        ArrayList<String> name = new ArrayList<>();
        
        
        for(int i=0;i<3;i++){
            name.add(sc.next());
            
        }



        String filePath = "/Users/eunsukkim/Desktop/textkim.txt";
//        String text = "weawegawegaweg awegaweg f\nwefwef\newf";
        
        
        String text = "";
        for(int i =0;i<name.size();i++){
            text+=name.get(i)+"\n";
            
        }

        write(filePath, text);

        try {
            String result = read(filePath, z );
        } catch (IOException e) {
            throw new RuntimeException(e);
        }



//            System.out.println("파일 내용: " + result);
//        } catch (IOException e) {
//            System.out.println("파일 읽기 중 오류 발생: " + e.getMessage());
//        }
    }

    public static void write(String filePath, String text) {
        try {
            OutputStream os = new FileOutputStream(filePath);
            Writer writer = new OutputStreamWriter(os, StandardCharsets.UTF_8);

            writer.write(text);
            writer.flush();
            writer.close();

            System.out.println("파일에 문자열을 저장했습니다.");
        } catch (IOException e) {
            System.out.println("파일 쓰기 중 오류 발생: " + e.getMessage());
        }
    }

    public static String read(String filePath, z21 z) throws IOException {
String returnstring = "";



BufferedReader br = new BufferedReader(new FileReader( "/Users/eunsukkim/Desktop/textkim.txt"));
while(true){
    String line = br.readLine();
    if(line==null) break;
    z.arr.add(line);

    returnstring+=line+"\n";

}
        System.out.println("여기부터는 저장된곳");
        System.out.println(z.arr);

        return returnstring;



    }
}

관련글 더보기

댓글 영역