写入文件和 I/O

Writing to files and I/O

我正在尝试编写一个程序来获取用户输入,然后将其写入名为 userStrings.txt 的输出文件。我也试图在用户输入 'done' 后停止处理,但我不确定如何完成此操作。

这是我的代码:

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

public class Murray_A04Q2 {
    public static void main(String[] args) throws IOException {


    // Name of the file
        String fileName = "userStrings.txt";

        Scanner scan = new Scanner(System.in);

        try {
            // FileReader reading the text files in the default encoding.
                FileWriter fileWriter = new FileWriter("userStrings.txt");

            // Wrapping FileReader in BufferedReader.
                BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

                bufferedWriter.write("A string");
                bufferedWriter.write("Another string");
                bufferedWriter.write("Yet more text...");
                System.out.println("Enter something, DONE to quit: ");
                String input = scan.nextLine();

            // Closing file
                bufferedWriter.close();
        }

        catch (IOException ex){
            System.out.println("Error writing to file " + "userStrings.txt" + "");
        }


    } // End of method header
} // End of class header

为了写入文件,我还使用System.out.println吗? bufferedWriter.write 是必要的吗?我只是想了解 I/O 并更好地写入文件。

谢谢!

In order to write to a file, do I still use System.out.println?

没有。写入标准输出,而不是您的文件。

如果您使用 println,那么您需要用 PrintWriter 包裹您的 BufferedWriter。 (查看 System class 的 javadoc,其中记录了 out 字段。)

and is the bufferedWriter.write even necessary?

如果您要直接写入 BufferedWriter 那么是的,这是必要的,尽管您可能需要适当的 "end of line" 序列。这就是它变得有点混乱的地方,因为不同的平台有不同的原生 "end of line" 序列。 (如果您使用 PrintWriterprintln 方法会选择正确的一个用于执行平台。)

I'm also trying to stop the processing once the user inputs 'done', but I'm not sure how to accomplish this.

提示:阅读 Scanner class 和 System.in

在您从控制台获取输入的正下方,运行 一个 while 循环来测试 input 不等于 "done"。在 while 循环中,将 input 添加到您的文件并获取下一行输入。

while(!input.toLowerCase().Equals("done"))
{
    bufferedWriter.write(input);
    input = scan.nextLine();
}