Java 扫描器与 2 hasNext()

标签 java csv java.util.scanner reader

我想从 CSV 文件恢复对象。我需要知道扫描仪是否有 2 个下一个值:scanner.hasNext()

问题是我的访问构造函数有两个参数,我需要确保 我的 csv 文件中至少还剩下 2 个。

相关代码如下:

    /**
 * 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();
}

提前致谢

最佳答案

hasNext() 也可以采用一个模式,这提供了一种很好的方法来检查这一点:

String pattern = ".*,.*";
while (scan.hasNext(pattern)) {
  ...
}

关于Java 扫描器与 2 hasNext(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28977021/

相关文章:

java - 尝试 PUT 方法时出现错误 405 (Jersey/Java) : Method Not Allowed

java - 面对: The method readLine() is undefined for the type String

java - 圆碰撞错误,圆绕不动的圆运行

php - CSV 或 Mysql 用于静态数据?

java - 需要帮助使用 java 读取文件、插入修剪命令、编辑字符串,然后将文件保存为输出

Java Scanner 输入困境。自动输入,不允许用户输入

Java 字节码操作和 Java 反射 API?

c# - 使用 LINQ 将 SQL 表转为 CSV

.net - 跳过 FileHelper 中的列

java - while 循环输入?