Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using delimiter when reading a file

Tags:

java

delimiter

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

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();
like image 545
Robert Spratlin Avatar asked Jan 09 '13 17:01

Robert Spratlin


People also ask

What is a delimiter in a file?

A delimiter separates the data fields. It is usually a comma, but can also be a pipe, a tab, or any single value character. An enclosing character occurs at the beginning and the end of a value. It is sometimes called a quote character (because it is usually double quotes), but you can use another character instead.

Is there delimiter in text file?

Data in a delimited text file is arranged in rows and columns, with one entry per row. Each column is separated from the next by a field separator character. The following file snippet illustrates characteristics common to many delimited files.


1 Answers

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

   title = read.next();
   category = read.next();
   runningTime = read.next();
   year = read.next();
   price = read.next();
like image 160
muffy Avatar answered Sep 28 '22 01:09

muffy