Ray Nim
Ray Nim

Reputation: 3

Reading CSV File Using Scanner Class Error

I have an original code that came from a Java book example. The program simply reads a text file ("clients.txt"). However, I would like to modify the "clients.txt" into a "clients.csv" and have the program read ".csv" file instead. I have parsed the data with "," as the delimiter according to this format and added/updated two lines of code in the ReadTextFile.java file below only:

Added/updated Code:

input = new Scanner( new File( "clients.csv" ) );
input.useDelimiter(",");    

Thought that this is a simple modification from reading a .txt file to a .csv file, I got a NoSuchElementException or File improperly formed print message.

I know that there are other classes that I can use such as BufferedReader and/or CsvReader Class but just wanted to figure out why input.useDelimiter() method is not working here.

=====================

Error Message

Process started >>>
<<< Process finished. (Exit code 0)
java ReadTextFileTest
Process started >>>
Account   First Name  Last Name      Balance
File improperly formed.
<<< Process finished. (Exit code 1)

=====================

ReadTextFile.java

import java.io.File;
import java.io.FileNotFoundException;
import java.lang.IllegalStateException;
import java.util.NoSuchElementException;
import java.util.Scanner;

public class ReadTextFile
{
   private Scanner input;

   public void openFile()
   {
      try
      {

         // Orig code: input = new Scanner( new File( "clients.txt")    
         input = new Scanner( new File( "clients.csv")); // added/updated
         input.useDelimiter(",");                          // added 

      } 
      catch ( FileNotFoundException fileNotFoundException )
      {
         System.err.println( "Error opening file." );
         System.exit( 1 );
      } 
   } 


   public void readRecords()
   {

      AccountRecord record = new AccountRecord();

      System.out.printf( "%-10s%-12s%-12s%10s\n", "Account",
     "First Name", "Last Name", "Balance" );

      try 
      {
         while ( input.hasNext() )
         {
            record.setAccount( input.nextInt() ); // read account number
            record.setFirstName( input.next() ); // read first name
            record.setLastName( input.next() ); // read last name
            record.setBalance( input.nextDouble() ); // read balance

            System.out.printf( "%-10d%-12s%-12s%10.2f\n",
           record.getAccount(), record.getFirstName(),
           record.getLastName(), record.getBalance() );
         } 
      } 
      catch ( NoSuchElementException elementException )
      {
         System.err.println( "File improperly formed." );
         input.close();
         System.exit( 1 );
      } 
      catch ( IllegalStateException stateException )
      {
         System.err.println( "Error reading from file." );
         System.exit( 1 );
      } 
   } 

   public void closeFile()
   {
      if ( input != null )
         input.close(); 
   } 
} 

=====================

ReadTextFileTest.java

public class ReadTextFileTest
{
   public static void main( String args[] )
   {
      ReadTextFile application = new ReadTextFile();

      application.openFile();
      application.readRecords();
      application.closeFile();
   } 
} 

=====================

AccountRecord.java

public class AccountRecord
{
   private int account;
   private String firstName;
   private String lastName;
   private double balance;

   public AccountRecord() 
   {
      this( 0, "", "", 0.0 );
   } 

   public AccountRecord( int acct, String first, String last, double bal)
   {
      setAccount( acct );
      setFirstName( first );
      setLastName( last );
      setBalance( bal );
   } 
   public void setAccount( int acct ) { account = acct; } public int getAccount() { return account; }

   public void setFirstName( String first )
   {
      firstName = first;
   } 
   public String getFirstName() 
   { 
      return firstName; 
   } 
   public void setLastName( String last )
   {
      lastName = last;
   } 
   public String getLastName() 
   {
      return lastName; 
   } 
   public void setBalance( double bal )
   {
      balance = bal;
   } 
   public double getBalance() 
   { 
      return balance; 
   } 
} 

===========================

clients.txt (original file)

100 Bob Jones 24.98
200 Steve Doe -345.67
300 Pam White 0.00
400 Sam Stone -42.16
500 Sue Rich 224.62
100 Bob Jones -4.98    
200 Steve Doe 45.67

===============================================

clients.csv (change from ".txt" to ".csv" file)

100,Bob,Jones,24.98
200,Steve,Doe,-345.67
300,Pam,White,0.00
400,Sam,Stone,-42.16
500,Sue,Rich,224.62
100,Bob,Jones,-4.98
200,Steve,Doe,45.67

Upvotes: 0

Views: 1123

Answers (2)

Aditya Singh
Aditya Singh

Reputation: 2453

Your CSV file must be:

100,Bob,Jones,24.98,200,Steve,Doe,-345.67,300,Pam,White,0.00,400,Sam,Stone,-42.16,500,Sue,lastName,0.00  

Your CSV file cannot contain \n(linebreaks) as it will be an illegal character for your program. Coz your delimiter is , and not \n.

But to keep your clients.csv file as it is, you can use the following method:

input.useDelimiter(Pattern.compile(",|\\n|\\r"));

Upvotes: 0

Peter Neyens
Peter Neyens

Reputation: 9820

Your code fails when it tries to read the first balance. Since your delimiter is only a comma (,). It tries to read 24.98<new-line>200 as a double.

We can use a comma and a new line character as delimiters using a Pattern.

import java.util.regex.Pattern;

Pattern delimiter = Pattern.compile(",|\\s"); 
input = new Scanner(new File("clients.csv")).useDelimiter(delimiter);

There are some trailing spaces on a line of your files, so I used ,|\\s otherwise you can use ,|\n or ,|\n|\r\n.

Upvotes: 0

Related Questions