java - 读取文件时使用定界符

标签 java delimiter

我没有使用定界符的经验,我需要读取一个文本文件,该文件存储了多个对象,这些对象的数据存储在以逗号 (",") 分隔的单行中。然后使用单独的字符串创建一个新对象,该对象被添加到数组列表中。

Amadeus,Drama,160 Mins.,1984,14.83
As Good As It Gets,Drama,139 Mins.,1998,11.3
Batman,Action,126 Mins.,1989,10.15
Billy Elliot,Drama,111 Mins.,2001,10.23
Blade Runner,Science Fiction,117 Mins.,1982,11.98
Shadowlands,Drama,133 Mins.,1993,9.89
Shrek,Animation,93 Mins,2001,15.99
Snatch,Action,103 Mins,2001,20.67
The Lord of the Rings,Fantasy,178 Mins,2001,25.87

我正在使用 Scanner 读取文件,但是我收到一个没有找到行的错误,并且整个文件存储在一个字符串中:

Scanner read = new Scanner (new File("datafile.txt"));
read.useDelimiter(",");
String title, category, runningTime, year, price;

while (read.hasNext())
{
   title = read.nextLine();
   category = read.nextLine();
   runningTime = read.nextLine();
   year = read.nextLine();
   price = read.nextLine();
   System.out.println(title + " " + category + " " + runningTime + " " +
                      year + " " + price + "\n"); // just for debugging
}
read.close();

最佳答案

使用 read.next() 而不是 read.nextLine()

   title = read.next();
   category = read.next();
   runningTime = read.next();
   year = read.next();
   price = read.next();

关于java - 读取文件时使用定界符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14242984/

相关文章:

java - 如何根据空格数量分割字符串

java - 如果字符串末尾有逗号,如何删除逗号

c++ - C++文字中的分隔符十和单位

java - QRcode 和 BarQRCode itextpdf

java - Eclipse 的 Java 格式化程序能否以不同于新 block 的方式缩进换行?

python-3.x - 如何完成这个Python脚本来操作制表符分隔文件中的数据?

c++ - 在 C++ 中使用分隔符获取输入

delphi - 在 TStringList 中添加超过 1 个分隔符

java - 将迭代器传递给方法

java - 如何更改 Sikuli 中的 Settings.MinSimilarity?