Java bufferedreader搜索文本文件?
文件txt: 1 aaa 100 其中插入数字1表示输出为空 爪哇:Java bufferedreader搜索文本文件?,java,Java,文件txt: 1 aaa 100 其中插入数字1表示输出为空 爪哇: private static void SearchForId() { try { Scanner scanner = new Scanner(System.in); System.out.println("Inter Id"); String id = scanner.next(); BufferedReader
private static void SearchForId() {
try {
Scanner scanner = new Scanner(System.in);
System.out.println("Inter Id");
String id = scanner.next();
BufferedReader Buffer = new BufferedReader(new FileReader(new File(
"D://Save.txt")));
String line = null;
while ((line = Buffer.readLine()) != null) {
if (line.trim().equals(id)) {
System.out.println(line + "\n");
}
}
} catch (Exception e) {
System.out.print("" + e);
}
}
问题出在哪里。?如果我正确理解了问题,您不需要
扫描仪
这里:
private static void SearchForId() {
try {
System.out.println("Inter Id");
BufferedReader Buffer = new BufferedReader(new FileReader(new File(
"D://Save.txt")));
String[] line = Buffer.readLine().split(" ");
int a = Integer.parseInt(line[0]);
String s = line[1];
int b = Integer.parseInt(line[2]);
} catch (Exception e) {
System.out.print("" + e);
}
}
你可以这样试试
private static void SearchForId() {
try {
Scanner scanner = new Scanner(System.in);
System.out.println("Inter Id");
String id = scanner.next();
BufferedReader Buffer = new BufferedReader(new FileReader(new File(
"D://Save.txt")));
String line = null;
while ((line = Buffer.readLine()) != null) {
String arr[] = line.split(" ");
for (int i = 0; i < arr.length; i++) {
if (arr[i].trim().equals(id)) {
System.out.println(line);
}
}
}
} catch (Exception e) {
System.out.print("" + e);
}
private static void SearchForId(){
试一试{
扫描仪=新的扫描仪(System.in);
System.out.println(“内部Id”);
字符串id=scanner.next();
BufferedReader Buffer=新BufferedReader(新文件读取器)(新文件读取器(
“D://Save.txt”);
字符串行=null;
而((line=Buffer.readLine())!=null){
字符串arr[]=line.split(“”);
对于(int i=0;i
出了什么问题,您希望它做什么?在文件中查找号码为什么要呼叫println()
有一个额外的换行符?它的要点是打印行-它已经添加了一个换行符。在没有扫描仪
声明的情况下,它应该如何编译?当它只读取一行时,它如何准确地搜索文件?如何使用readLine()
而不检查结果是否为空?或split()
如果不检查返回的数组的长度?@EJP file.txt在问题中正好包含一行和三个数字,因此检查null
在这里是无用的。你根本不理解这个问题,更不用说正确了。OP编写了一个循环。他正在尝试扫描一个文件。你的代码读取一行并分配给两行否则不使用变量。它不会要求用户提供ID。它不会打印结果。它与问题完全无关。