以某种格式读取java文件时出现问题

3j86kqsm  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(310)

我正在从一个文件中读取文本,我在尝试读取时遇到了问题 List 1 以及 List 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];
jljoyd4f

jljoyd4f1#

您的代码有多个问题,比如@henry说您的字符串只包含文件的最后一行,而且您误解了 split() 因为它需要一个正则表达式作为参数。
我建议您使用下面的示例,因为它有效,而且比您的方法快得多。
启动示例:

// 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 作为构造函数中的参数。这仅用于转换以下内容 FileInputStreamReader .
为什么要这样做?那是因为 InputStreamReader . 一 InputStream 返回原始值和 Reader 将其转换为可读字符。看看他们之间的区别 InputStream 以及 Reader .
看下一行:

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

创建一个具有如下方法的变量数组 add() 以及 get(index) . 查看数组和列表的区别。
最后一个:

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

此行添加 line 并向其中添加新行。 "\r\n" 都是特殊人物。 \r 结束当前行并 \n 创建新行。
你也只能用 \n 但是添加 \r 在它前面是更好的,因为它支持更多的操作系统,比如linux在运行时可能会有问题 \r 未命中。

相关

使用bufferedreader读取文本文件

相关问题