解析Java无法读取文本文件
我正在读一本书。txt文件并搜索一个单词,但程序仅以Process finished with exit code 0
结束
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class LogParser {
static Scanner file;
static ArrayList text = new ArrayList();
static String path = new String();
static String check = new String();
private static int a = 0;
static Scanner inpunt = new Scanner(System.in);
public static void main (String[] args) {
System.out.println("Input path to file");
path = inpunt.nextLine();
File texts = new File(path);
try {
file = new Scanner(new File(path));
} catch (Exception e) {
System.out.println("Can't open file");
}
try {
while (file.hasNext()) {
text.add(a, file.nextLine());
check = text.get(a).toString();
if (check.contains("cap"))
System.out.println("Allert!!!!!!!!!!!!!!!!!!!!!!!!!!!" + text.get(a));
a = a + 1;
}
} catch (Exception e) {
// System.out.println("Can't open file");
if (file.toString().contains("cap"))
System.out.println("cap" + "Path to file: " + path);
System.out.println(text.size());
}
}
}
这本书的正文。txt文件是:
let's try read this cap
如果我尝试打开一个xml文件,一切都正常。我的问题只存在于txt文件中
# 1 楼答案
如注释中所述,未设置path变量。您试图创建一个新文件,并传入一个尚未实例化的路径