【问题标题】:Trouble reading a file in java in a certain format以某种格式在java中读取文件时遇到问题
【发布时间】:2021-04-09 10:23:18
【问题描述】:

我正在从文件中读取文本,但在尝试将 List 1List 2 读入 2 个不同的 String 时遇到了问题。 * 表示第一个列表的结束位置。我尝试过使用数组,但数组只存储最后一个 * 符号。

List 1
Name: Greg
Hobby 1: Swimming
Hobby 2: Football
*
List 2
Name: Bob
Hobby 1: Skydiving
*

到目前为止,这是我尝试过的:

String s = "";
try{
Scanner scanner = new Scanner(new File("file.txt"));
while(scanner.hasnextLine()){
s = scanner.nextLine();
}
}catch(Exception e){
e.printStackTrace}
String [] array = s.split("*");
String x = array[0];
String y = array[1];

【问题讨论】:

  • 提示:在while循环之后s只包含文件的最后一行。
  • 哦,我明白了,还有其他方法可以解决这个问题吗?

标签: java file java.util.scanner


【解决方案1】:

您的代码有多个问题,例如 @Henry 说您的字符串仅包含文件的最后一行,而且您误解了 split(),因为它需要 RegularExpression 作为参数。

我建议您使用以下示例,因为它有效并且比您的方法快得多。


启动示例:

// create a buffered reader that reads from the file
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("test.txt")));

// create a new array to save the lists
ArrayList<String> lists = new ArrayList<>();

String list = ""; // initialize new empty list
String line; // initialize line variable

// read all lines until one becomes null (the end of the file)
while ((line = reader.readLine()) != null) {
    // checks if the line only contains one *
    if (line.matches("\\s*\\*\\s*")) {
        // add the list to the array of lists
        lists.add(list);
    } else {
        // add the current line to the list
        list += line + "\r\n"; // add the line to the list plus a new line
    }
}

说明

我将再次解释难以理解的特殊行。


看第一行:

BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("test.txt")));

这一行创建了一个BufferedReader,它与Scanner 几乎相同,但它更快,并且没有Scanner 那么多的方法。对于这种用法,BufferedReader 绰绰有余。

然后它将InputStreamReader 作为构造函数中的参数。这只是将以下FileInputStream 转换为Reader

为什么要这样做?那是因为InputStreamReaderInputStream 返回原始值,Reader 将其转换为人类可读的字符。见the difference between InputStream and Reader


看下一行:

ArrayList<String> lists = new ArrayList<>();

创建具有add()get(index) 等方法的变量数组。见the difference of arrays and lists


最后一个:

list += line + "\r\n";

这一行将line 添加到当前列表中并在其中添加一个新行。

"\r\n" 是特殊字符。 \r 结束当前行,\n 创建一个新行。

您也可以只使用\n,但在它前面添加\r 会更好,因为它支持更多的操作系统,如Linux,当\r 未命中时可能会出现问题。


相关

Using BufferedReader to read Text File

【讨论】:

  • 我明白了,谢谢。在我将它实现到我自己的代码中之前,我需要更多地研究正则表达式。是否可以阻止缓冲读取器从 *(星号) 进一步读取并将其之前的值分配给一个字符串,并将其之后的值分配给不同的字符串?
  • @m1759 据我了解您的问题,这已经完成。 ArrayList 在运行示例时包含两个值:一个在星号之前,一个在星号之后,如果有更多列表,每个列表都将位于一个自己的字符串中。您可以通过lists.get(0)lists.get(1) 访问它们(这与array[0]array[1] 相同)。如果您以前从未使用过 List,我建议您阅读 this 关于 ArrayList 的文章。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-07-06
  • 2012-09-28
  • 2017-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-05
相关资源
最近更新 更多