【问题标题】:How to find and read a line in a file with a specific value? [closed]如何在具有特定值的文件中查找和读取一行? [关闭]
【发布时间】:2014-09-01 19:06:02
【问题描述】:

我有一个格式如下的输入文本文件:

11111, "Top Secret Twenty One - Janet Evanovich", 8.99
22222, "W Is For Wasted - Sue Grafton", 9.95
33333, "Gray Mountain - John Grisham", 14.95
44444, "Revival - Stephen King", 12.95

如何将“1111”、“Top Secret 21 - Janet Evanovich”和“8.99”作为不带引号和逗号的单独变量读取?

我基本上是在尝试在文件中搜索 bookID(又名“11111”)。

【问题讨论】:

  • 你试过了吗?可以提供代码吗?通过使用readline 读取每一行并使用substringindexOf 搜索适当的结果,这可能可以实现
  • 代码显示什么 - 查找 Reader.readLine? String.indexOf?使用循环?遇到编译器错误或运行时异常?除非这是一项学校作业,否则我会 1) 不使用 Java(因为有更好的工具来完成这项任务)和/或; 2) 使用 CSV 库。

标签: java file csv


【解决方案1】:

这是我在课堂上学到的:

import java.util.*; // for the scanner
import java.io.*; // for the object

File f = new File("<filename>");
Scanner input = new Scanner(f);

input.useDelimiter(",|\"|\n"); // delimiters are commas, quotes, and newlines

input.nextInt(); //reads 1111 as an integer
input.next(); // reads the empty space (needed because " " wasn't declared as a delimiter)
input.next(); // reads in Top Secret Twenty One - Janet Evanovich as a String.
input.next(): // reads in the empty space
input.nextDouble(); // reads in 8.99 as a double

要更改 Java 的默认分隔符(空格、制表符、换行符),我使用了以下内容:

Scannervariable.useDelimiter(",|\"|\n");

此命令使用逗号、引号和换行符作为分隔符,忽略它们并移动到下一个标记。该|意思是“或”。您可以根据您要读取的内容使用以下 Scanner 方法:

next()、nextInt()、nextDouble() 或 nextLine()

您可以在线查找每种方法的确切功能。

【讨论】:

  • 非常有帮助,谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-05
  • 1970-01-01
  • 2012-05-12
  • 1970-01-01
  • 2011-09-16
  • 1970-01-01
相关资源
最近更新 更多