Java,将控制台内容写入文件

问题描述 投票:1回答:2

我正在测试,尝试将控制台内容写入文件,但是当我运行应用程序时,生成的文本文件为空。我希望用户在用户输入完详细信息后输入一些详细信息。我希望用户输入文件名以将控制台内容写入。但是,生成的文件为空。

public void test() {
    boolean check=true;
    int i=0;
    for (i=0;i<5;i++) {
        System.out.println("Enter your name");
        String name=Keyboard.readInput();
        System.out.println("Name:"+ name);
        System.out.println("Enter your age");
        int age=Integer.parseInt(Keyboard.readInput());
        System.out.println("Age:"+age);
    }

    out.println("enter 1 to save to file");
    int num=Integer.parseInt(Keyboard.readInput());
    if (num == 1) {
        out.println("Enter the file name to write to:\n");
        String filename = Keyboard.readInput();
        File myfile = new File(filename);

        try {
                PrintStream out = new PrintStream(new FileOutputStream(myfile));
                System.setOut(out);
        } catch (IOException e) {
            out.println("Error:" + e.getMessage());
        }
    }
}
java
2个回答
2
投票

您只创建文件而不在文件上写任何文件为空的原因。创建文件后,您必须通过PrintStream.println()方法在文件上写一些内容。

try {
    PrintStream out = new PrintStream(new FileOutputStream(myfile));
    out.println("some text"); // it will write on File

    // OR if you setOut(PrintSrtream) then
    System.setOut(out);
    System.out.println("some text");// this will also write on file
} catch (IOException e) {
    out.println("Error:" + e.getMessage());
}

0
投票

Java 8+

static void writeFile(String path, String...lines) throws IOException {
    Files.write(
        Paths.get(path), 
        Arrays.asList(lines));
}
© www.soinside.com 2019 - 2024. All rights reserved.