본문 바로가기

Algorithm/BaekJOON(Java)

파일 입출력


  임의의 내용을 사용자로부터 입력받아 파일로 출력하기



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
 
public class File {
    
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String FileName = "";
 
        System.out.println("저장할 파일의 이름을 입력하세요. > ");
        FileName = scan.nextLine();

        System.out.println("저장할 파일의 내용을 입력하세요 , exit 입력시 종료됩니다. > ");
        try {
            BufferedWriter out = new BufferedWriter(new FileWriter(FileName + ".txt",true)); // true (이어쓰기)
            while(scan.hasNext()) {
                String text = scan.next();
if(text.equals("exit")) {
                    scan.close();
                    break;
                }
                out.write(text);
                out.newLine();
            }
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
}
 

cs