使用扫描仪读取 CSV 文件 Class 错误

Reading CSV File Using Scanner Class Error

我有一个来自 Java 书籍示例的原始代码。该程序只是读取一个文本文件 ("clients.txt")。但是,我想将 "clients.txt" 修改为 "clients.csv" 并让程序改为读取“.csv”文件。我已经按照这种格式解析了以“,”为分隔符的数据,并且仅在下面的ReadTextFile.java文件中添加了added/updated两行代码:

Added/updated代码:

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

以为这是从 .txt 文件读取到 .csv 文件的简单修改,我得到了 NoSuchElementExceptionFile improperly formed 打印消息。

我知道还有其他 类 可以使用,例如 BufferedReader and/or CsvReader Class 但我只是想弄清楚为什么 input.useDelimiter() 方法在这里不起作用。

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

错误信息

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(原文件)

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(从“.txt”文件更改为“.csv”文件)

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

您的代码在尝试读取第一个余额时失败。由于您的分隔符只是一个逗号 (,)。它尝试将 24.98<new-line>200 读取为双精度数。

我们可以使用逗号和换行符作为分隔符,使用 Pattern.

import java.util.regex.Pattern;

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

你的文件一行中有一些尾随空格,所以我使用了 ,|\s 否则你可以使用 ,|\n,|\n|\r\n.

您的 CSV 文件必须是:

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  

您的 CSV 文件不能包含 \n(换行符),因为它对于您的程序来说是非法字符。因为你的分隔符是 , 而不是 \n

但要保持 clients.csv 文件不变,您可以使用以下方法:

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