我正在从一个文件中读取文本,我在尝试读取时遇到了问题 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];
1条答案
按热度按时间jljoyd4f1#
您的代码有多个问题,比如@henry说您的字符串只包含文件的最后一行,而且您误解了
split()
因为它需要一个正则表达式作为参数。我建议您使用下面的示例,因为它有效,而且比您的方法快得多。
启动示例:
解释
我要再解释一下那些很难理解的特殊台词。
看第一行:
这条线创建一个
BufferedReader
这几乎和Scanner
但它的速度要快得多,而且没有一个Scanner
. 对于这种用法BufferedReader
已经足够了。那就需要一个
InputStreamReader
作为构造函数中的参数。这仅用于转换以下内容FileInputStream
到Reader
.为什么要这样做?那是因为
InputStream
≠Reader
. 一InputStream
返回原始值和Reader
将其转换为可读字符。看看他们之间的区别InputStream
以及Reader
.看下一行:
创建一个具有如下方法的变量数组
add()
以及get(index)
. 查看数组和列表的区别。最后一个:
此行添加
line
并向其中添加新行。"\r\n"
都是特殊人物。\r
结束当前行并\n
创建新行。你也只能用
\n
但是添加\r
在它前面是更好的,因为它支持更多的操作系统,比如linux在运行时可能会有问题\r
未命中。相关
使用bufferedreader读取文本文件