在读取文件时使用分隔符

我几乎没有使用分隔符的经验,我需要读取一个文本文件,该文件存储多个对象,其数据以逗号(“,”)分隔的单行存储。 然后使用单独的字符串来创建添加到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(); 

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

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

我想你想调用.next() ,它返回一个String而不是.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(); 

你应该使用next(); 你在哪里使用nextLine();

看一下教程: http : //docs.oracle.com/javase/tutorial/essential/io/scanning.html

请注意以下几行:

 try { s = new Scanner(new BufferedReader(new FileReader("xanadu.txt"))); while (s.hasNext()) { System.out.println(s.next()); } 

您还可以使用String.split()函数将字符串转换为字符串数组,然后针对您的值迭代每个字符串。

如何将逗号分隔的String转换为ArrayList? 有关详细信息,请参阅此

一个问题是:

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

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

你正在做nextLine()三次。 我想你需要做的是,读取线和分割线。