我想从CSV文件中还原一个对象。我需要知道扫描器是否有2个下一个值: scanner.hasNext()
问题是,我的访问构造函数接受两个参数,我需要确保至少还有两个在我的csv文件中。
以下是相关代码:
/**
* method to restore a pet from a CSV file.
* @param fileName the file to be used as input.
* @throws FileNotFoundException if the input file cannot be located
* @throws IOException if there is a problem with the file
* @throws DataFormatException if the input string is malformed
*/
public void fromCSV(final String fileName)
throws FileNotFoundException, IOException, DataFormatException
{
FileReader inStream = new FileReader(fileName);
BufferedReader in = new BufferedReader(inStream);
String data = in.readLine();
Scanner scan = new Scanner(data);
scan.useDelimiter(",");
this.setOwner(scan.next());
this.setName(scan.next());
while (scan.hasNext()) {
Visit v = new Visit(scan.next(), scan.next());
this.remember(v);
}
inStream.close();
}提前感谢
发布于 2015-03-11 01:40:25
hasNext()也可以采用一种模式,它提供了一种很好的检查方法:
String pattern = ".*,.*";
while (scan.hasNext(pattern)) {
...
}发布于 2015-03-11 01:31:22
为了直接解决我认为您要问的问题:您可以在while循环中检查scan.hasNext()。
public void fromCSV(final String fileName) throws FileNotFoundException, IOException, DataFormatException
{
FileReader inStream = new FileReader(fileName);
BufferedReader in = new BufferedReader(inStream);
String data = in.readLine();
Scanner scan = new Scanner(data);
scan.useDelimiter(",");
this.setOwner(scan.next());
this.setName(scan.next());
while (scan.hasNext()) {
String first = scan.next();
if(scan.hasNext()) {
String second = scan.next();
Visit v = new Visit(first, second);
this.remember(v);
}
}
inStream.close();
}虽然我认为您是在询问while循环中使用scan.hasNext()的情况,但您也应该在this.setOwner(scan.next())和this.setName(scan.next())之前进行检查。
也许更好的方法是采取另一种方法来解决这个问题,就像Hovercraft在评论中所建议的那样。更好的是,因为这是一个CSV文件,所以使用公域CSV或露天矿这样的库可以省去很多麻烦。
https://stackoverflow.com/questions/28977021
复制相似问题