这是用户在 2024-9-30 16:42 为 https://edstem.org/au/courses/17312/lessons/55794/slides/377653 保存的双语快照页面,由 沉浸式翻译 提供双语支持。了解如何保存?

10.2.2 Writing to a file
10.2.2 写入文件

When writing to a file, the following steps are used:
写入文件时,使用以下步骤:

  1. Open the file. 打开文件。

  2. Write to the file. 写入文件。

  3. Close the file. 关闭文件。

The last step of closing the file is crucial to ensure that the data stored to the file is persistent and the file is available for another user who wishes to access the file.
关闭文件的最后一步对于确保存储到文件的数据是持久性的,并且该文件可供希望访问该文件的其他用户使用至关重要。

When working with files there are possible scenarios where one of the actions listed above could fail. These scenarios need to be handled when working with files. As such, all the classes that we use to work with files throw checked exceptions, meaning that when we use them in our programs we need to include the code to handle these exceptions.
在处理文件时,可能会有上述操作之一失败的情况。在处理文件时,需要处理这些情况。因此,我们用于处理文件的所有类都会引发检查异常,这意味着当我们在程序中使用它们时,我们需要包含处理这些异常的代码。

In this part of our lesson we will discuss two approaches that can be used to write to a text file. We will outline two classes from the Java API that new programmers should be able to easily understand and apply.
在这部分课程中,我们将讨论两种可用于写入文本文件的方法。我们将概述 Java API 中的两个类,新程序员应该能够轻松理解和应用它们。

FileWriter class FileWriter 类

The FileWriter class is part of the java․io package, which must be imported when using it in a program. The FileWriter class has the methods of write() and append(), which allow for data to be written to a file. When an object of the class is created, the programmer must specify the name of the file to be written to. If the file doesn't exist, it is created, and if the file does exist, depending on the method, data is either overwritten or appended. Let's see an example of this in code:
FileWriter 类是 java.io 包的一部分,在程序中使用时必须导入该类。FileWriter 类具有 write()append() 方法,这些方法允许将数据写入文件。创建类的对象时,程序员必须指定要写入的文件的名称。如果文件不存在,则创建该文件,如果文件存在,则根据方法,数据将被覆盖或附加。让我们看看代码中的一个示例:

import java.util.Scanner; import java.io.FileWriter; public class WriteFile { public static void main(String[] args) { boolean flag = true; Scanner console = new Scanner(System.in); try { FileWriter writer = new FileWriter("temp.txt"); do { System.out.println("Enter text to append to file..."); String value = console.nextLine(); value += "\n"; writer.append(value); try { System.out.println("Continue adding text to file (y or n)?"); char response = console.nextLine().trim().toLowerCase().charAt(0); if (response == 'n') { flag = false; writer.close(); } } catch (Exception e) { System.out.println("Please enter y or n only!"); } } while (flag); } catch (Exception e) { System.out.println("Error in writing to file! Exiting..."); } } }
Java 爪哇岛

Note the following: 请注意以下事项:

  • The above is not the best way to write to a file but it demonstrates how a file can be written to with dynamic input.
    以上不是写入文件的最佳方法,但它演示了如何使用动态输入写入文件。

  • Line 13, which creates the object of the FileWriter class, MUST appear inside a try block as it throws a checked exception, which must be handled.
    第 13 行(创建 FileWriter 类的对象)必须出现在 try 块中,因为它会引发必须处理的已检查异常。

  • Line 27 is extremely important. The file must be closed for the input to be persistent. Try commenting out line 27 by putting a // at the start of the line and run the program again to see the difference.
    27 号线非常重要。必须关闭该文件才能使输入持久化。尝试通过在行首放置 a 来注释掉第 27 行,然后再次运行程序以查看差异。

  • Uncomment Line 27 by deleting the // at the start.
    通过删除开头的 来取消对第 27 行的注释。

  • Line 18 appends a new line character to the data. The write() method of the FileWriter class doesn't insert a newline character. An alternative method of including a newline character is to use the PrintWriter class, as shown in the next section.
    第 18 行将新行字符附加到数据中。FileWriter 类的 write() 方法不插入换行符。包含换行符的另一种方法是使用 PrintWriter 类,如下一节所示。

  • The second try catch on Line 20 is to prevent the user entering blank input, which could crash the program when we call the charAt() method on Line 23.
    第 20 行的第二个 try catch 是为了防止用户输入空白输入,当我们在第 23 行调用 charAt() 方法时,这可能会使程序崩溃。

PrintWriter class PrintWriter 类

The PrintWriter class is also part of the java․io package, which must be imported when using it in a program. The PrintWriter class has the methods of print() and println(), which work exactly the same way as printing output on the screen using System.out. The println() method inserts a newline character at the end of the line. When an object of the PrintWriter class is created, the programmer must specify the name of the file to be written to. If the file doesn't exist, it is created. Unlike the FileWriter class, which could append, the PrintWriter object always overwrites the existing file and all data present is erased. It is possible to append but it requires the use of an additional class in conjunction called BufferedWriter, which is out of scope for this unit.
PrintWriter 类也是 java.io 包的一部分,在程序中使用该类时必须导入该类。PrintWriter 类具有 print()println() 方法,它们的工作方式与使用 System.out 在屏幕上打印输出的方式完全相同。println() 方法在行尾插入换行符。创建 PrintWriter 类的对象时,程序员必须指定要写入的文件的名称。如果文件不存在,则创建该文件。 与可以追加的 FileWriter 类不同,PrintWriter 对象始终覆盖现有文件,并且存在的所有数据都将被擦除。可以附加,但它需要结合使用一个名为 BufferedWriter 的附加类,这超出了本单元的范围。

Let's see an example of the PrintWriter in code. The following code is going to demonstrate a few things differently from the example shown above, namely:
让我们看一下代码中的 PrintWriter 示例。以下代码将演示与上面所示的示例不同的一些内容,即:

  • The code will show how we can write data that is stored in a data structure such as a collection.
    该代码将展示我们如何编写存储在数据结构(如集合)中的数据。

  • While the above code worked, it had one big flaw. If the program crashed during the writing process, the file would never be closed, causing all data written to be lost. So one approach to close the file is to use the finally block. This code will demonstrate how the finally block should be used when working with files.
    虽然上面的代码可以工作,但它有一个大缺陷。如果程序在写入过程中崩溃,则文件永远不会关闭,从而导致写入的所有数据丢失。因此,关闭文件的一种方法是使用 finally 块。此代码将演示在处理文件时应如何使用 finally 块。

import java.util.Scanner; import java.util.ArrayList; import java.io.PrintWriter; public class WriteFile { public static void main(String[] args) { boolean flag = true; Scanner console = new Scanner(System.in); try { PrintWriter writer = new PrintWriter("temp.txt"); try { ArrayList<String> values = new ArrayList<String>(); do { System.out.println("Enter text to append to file..."); values.add(console.nextLine()); try { System.out.println("Continue adding text to file (y or n)?"); char response = console.nextLine().trim().toLowerCase().charAt(0); if (response == 'n') flag = false; } catch (Exception e) { System.out.println("Please enter y or n only!"); } } while (flag); for (String temp : values) { writer.println(temp); } } finally { try { writer.close(); } catch (Exception e) { System.out.println("Error in closing file! Exiting..."); } } } catch (Exception e) { System.out.println("Error in writing to file! Exiting..."); } } }
Java 爪哇岛

Note the following: 请注意以下事项:

  • The code reads data stored in a collection and then uses the println() method in the PrintWriter class to write the data to the file.
    该代码读取存储在集合中的数据,然后使用 PrintWriter 类中的 println() 方法将数据写入文件。

  • Note the inclusion of the second try statement on Line 15. When using the finally block to close the file, since Line 14 declares the PrintWriter object and it must appear inside the try block, if we include a finally associated with this try on Line 56, this would give us a syntax error as the variable writer would be out of scope. And since a finally must appear with a try, we need to add a second try so we can include the finally nested inside the first try statement. (Note the second try doesn't have or need a catch statement!)
    请注意第 15 行包含第二个 try 语句。当使用 finally 块关闭文件时,由于第 14 行声明了 PrintWriter 对象并且它必须出现在 try 块中,如果我们在第 56 行包含与此 try 关联的 finally,这将给我们带来语法错误,因为变量编写器将超出范围。由于 finally 必须与 try 一起出现,因此我们需要添加第二个 try,以便我们可以将嵌套在第一个 try 语句中的 finally。(请注意,第二次 try 没有或不需要 catch 语句!

  • The use of the try-catch within the finally is optional (Line 42). However, it is good practice in case the program crashes due to the file not being found as the PrintWriter object was never created. This will prevent any further possible error from crashing our program.
    在 finally 中使用 try-catch 是可选的(第 42 行)。但是,如果由于从未创建 PrintWriter 对象而找不到文件,因此程序崩溃是一种很好的做法。这将防止任何进一步可能的错误使我们的程序崩溃。

The above are two possible ways to write to a file. We can see in the demonstrated code that both approaches do have some advantages and limitations. The choice of the appropriate class is again determined by the programmer and the requirements needed within the specifications. Either of the two classes should suffice for the requirements of our unit.
以上是写入文件的两种可能方法。我们可以在演示的代码中看到,这两种方法确实有一些优点和局限性。适当类的选择再次由程序员和规范中所需的要求决定。这两个类别中的任何一个都应该足以满足我们单位的要求。