在读取文件时使用分隔符 [英] Using delimiter when reading a file

查看:117
本文介绍了在读取文件时使用分隔符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have little experience using delimiters and i need to read a text file that stores several objects whose data is stored in single lines separate by commas (","). The seperate strings are then used to create a new object which is added to an 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读取文件,但是我发现没有找到行错误,整个文件存储在一个字符串中:

I am using Scanner to read the file, however i get a no line found error and the entire file is stored into one string:

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

Use read.next() instead of read.nextLine()

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

这篇关于在读取文件时使用分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆