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

10.2.4 Alternative ways to read a file
10.2.4 读取文件的其他方法

There are many different ways to read a file. The approach that we have discussed that uses the methods in the Scanner class works relatively well. However, the limitations become obvious when the data in the file is inconsistent or the format is slightly more complicated. For example, consider the below image, which depicts the content of a file:
读取文件的方法有很多种。我们讨论的使用 Scanner 类中的方法的效果相对较好。但是,当文件中的数据不一致或格式稍微复杂时,限制就会变得明显。例如,请考虑下图,它描述了文件的内容:

Inconsistent File Data - Toyota, 1999, Corolla, 4 door, sunroof-CD player- Alloy wheels-Tinted windows-alarm 2 Lexus, 2010, NX 5 door, alloy wheels-rear spoiler. 3 Mazda, 2015, RX8, 4 door, suicide doors

Looking at the above data, it is evidently talking about cars. However, looking closely, we can note that each entry does not contain the same amount of information. In fact the data contains two sets of delimited information. The first being the details about the cars, which use the comma (,) as the delimiter. The second is within each car's details, it outlines the features of each car, which uses the hypen (-) as the second delimiter. So using the approach we learned earlier would not be the most effective. A better approach would be to use the split() method in the String class as shown below.
从上面的数据来看,显然是在谈论汽车。但是,仔细观察,我们可以注意到每个条目不包含相同数量的信息。实际上,数据包含两组分隔信息。第一个是有关汽车的详细信息,它使用逗号 () 作为分隔符。第二个是在每辆车的详细信息中,它概述了每辆车的功能,它使用连字符 (-) 作为第二个分隔符。因此,使用我们之前学到的方法并不是最有效的。更好的方法是使用 String 类中的 split() 方法,如下所示。

The code is not runnable as we do not have a class called Car and we would need to include a method to create the text file first. However, if you would like to run it, try copying the code to the workspace environment and create the class called Car.
该代码不可运行,因为我们没有名为 Car 的类,我们需要先包含一个创建文本文件的方法。但是,如果要运行它,请尝试将代码复制到工作区环境并创建名为 Car 的类。

import java.util.Scanner; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; public class WriteFile { public static final String FILE_NAME = "cars.txt"; public void createFile(String fileName) { try { FileWriter writer = new FileWriter(FILE_NAME); try { writer.append("Toyota,1999,Corolla,4 Door,Sunroof-CD Player-Alloy Wheels-Tinted Windows-Alarm\n"); writer.append("Lexus,2010,NX,5 door, Alloy Wheels-RearSpoiler\n"); writer.append("Mazda,2015,RX8,4 door,Suicide doors\n"); } finally { try { writer.close(); } catch (Exception e) { System.out.println("Error in closing file! Exiting..."); } } } catch(Exception e) { System.out.println("Error in writing file! Exiting"); } } public static void main(String[] args) { WriteFile writeFile = new WriteFile(); writeFile.createFile(FILE_NAME); ArrayList<Car> cars = new ArrayList<>(); try { Scanner console = new Scanner(System.in); FileReader reader = new FileReader(FILE_NAME); try { Scanner fileInput = new Scanner(reader); int counter = 0; while (fileInput.hasNextLine()) { counter++; String[] lineContents = fileInput.nextLine().split(","); String make = lineContents[0]; int year = 0; try { year = Integer.parseInt(lineContents[1]); } catch (Exception e) { System.out.println("Error in car year of manufacture on Line" + counter + ". Skipping"); continue; } String model = lineContents[2]; String doors = lineContents[3]; String[] features = lineContents[4].split("-"); cars.add(new Car(make, year, model, doors, features)); } for (Car temp : cars) System.out.println(temp.display()); } finally { try { reader.close(); } catch (Exception e) { System.out.println("Error in closing file! Exiting..."); } } } catch (Exception e) { System.out.println("Error in reading the file! Exiting..."); } } }
Java 爪哇岛

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

  • Line 56 uses the split() method to split on the first delimiter to obtain an array of information for the car. We then use each index in the array to assign the values to the attribute of the object.
    第 56 行使用 split() 方法在第一个分隔符上进行拆分,以获取汽车的信息数组。然后,我们使用数组中的每个索引将值分配给对象的属性。

  • Line 59 uses a try-catch statement to ensure the data conversion is possible since the input is read as a String and needs to be converted to an integer. If an error occurs, note the use of the continue statement, which skips that line in the file and moves to the next.
    第 59 行使用 try-catch 语句来确保数据转换是可能的,因为输入被读取为 String 并且需要转换为整数。如果发生错误,请注意 continue 语句的使用,该语句会跳过文件中的该行并移动到下一行。

  • Note Line 70, we again use the split() method to split on the second delimiter. This gives us an array of features, which can be of any size. If we need to we can also perform additional operations on each index. This is not necessary in the code above.
    注意第 70 行,我们再次使用 split() 方法在第二个分隔符上进行拆分。这为我们提供了一系列特征,这些特征可以是任意大小的。如果需要,我们还可以对每个索引执行额外的操作。在上面的代码中,这不是必需的。

Using the split() method is a much more effective approach when reading information from a file as it gives us more control on the data and lowers the probability of errors in our program. Another alternative is the use of the substring() method in the String class, and while effective, it isn't as efficient as the split() method.
从文件中读取信息时,使用 split() 方法是一种更有效的方法,因为它让我们对数据有更多的控制权,并降低了程序出错的可能性。另一种选择是在 String 类中使用 substring() 方法,虽然有效,但它不如 split() 方法有效。