使用分隔符读取文件

8

我很少使用分隔符,需要读取一个文本文件,其中存储了一些对象,这些对象的数据以逗号(",")分隔在单行中。然后将分隔的字符串用于创建一个新对象,该对象添加到一个ArrayList中。

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();

1
Сй┐ућеread.next()УђїСИЇТў»nextLine()сђѓ - Jeroen Vannevel
6个回答

12

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

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

5
我认为您想调用.next()方法,它返回一个字符串,而不是使用.nextLine() 方法。您的.nextLine() 调用使当前行向后移动了。
Scanner read = new Scanner (new File("datafile.txt"));
   read.useDelimiter(",");
   String title, category, runningTime, year, price;

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

2

以上所有答案都是正确的,并且实际上相同。但是,每个人都应该记住一个重要点,即 Scanner 只有1024个缓冲区大小。这意味着如果分隔文本的长度更长,解析将停止。

因此,在给定的解决方案上进行小幅改进,使用 BufferedReader 而不是直接将文件传递给 Scanner 。示例:

    BufferedReader in = new BufferedReader(new FileReader("datafile.txt"), 16*1024);
    Scanner read = new Scanner(in);
    read.useDelimiter(",");
    String title, category, runningTime, year, price;

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

2

1

0

一个问题是:

while(read.hasNext())
   {
       title = read.nextLine();
       category = read.nextLine();
       runningTime = read.nextLine();

hasNext()

如果此扫描器在其输入中有另一个标记,则返回true。不是整行。您需要使用hasNextLine()

您正在执行三次nextLine()。我认为您需要做的是读取该行并拆分该行。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接