我有一个来自Java书籍示例的原始代码。该程序只是读取一个文本文件(“clients.txt”)。但是,我想将“clients.txt”修改为“clients.csv”,并将程序改为“.csv”文件。我已根据此格式使用“,”作为分隔符解析数据,并仅在下面的ReadTextFile.java
文件中添加/更新了两行代码:
添加/更新代码:
input = new Scanner( new File( "clients.csv" ) );
input.useDelimiter(",");
认为这是从阅读.txt
文件到.csv
文件的简单修改,我收到了NoSuchElementException
或File improperly formed
打印消息。
我知道我可以使用其他类,例如BufferedReader
和/或CsvReader
类,但只是想弄清楚为什么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)
=====================
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();
}
}
=====================
public class ReadTextFileTest
{
public static void main( String args[] )
{
ReadTextFile application = new ReadTextFile();
application.openFile();
application.readRecords();
application.closeFile();
}
}
=====================
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;
}
}
===========================
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
===============================================
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
答案 0 :(得分:0)
您的代码在尝试读取第一个余额时失败。由于您的分隔符只是逗号(,
)。它试图将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
。
答案 1 :(得分:0)
您的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"));