目标是至少编写一个其他(静态)方法(函数)供我的主程序调用。也许是一个 处理单行的方法。然后主程序可以重复调用,只要数据还在 在文件中。我无法为我的主程序创建一个函数来调用它。也许我的思维过程目前不起作用,有人可以帮忙吗?
我尝试创建一个名为 readFile() 的方法,如底部所示,但在使用扫描仪时收到错误
public static void main(String[] args) {
//Scanner for user input
Scanner input = new Scanner(System.in);
//String variables for inputting the filename of the file and sending the text to the output.
String inputFileName;
System.out.print("Enter the filename with your student data:\n");
inputFileName = input.nextLine();
File fileInput = new File(inputFileName);
//final BufferedReader in = new BufferedReader(new FileReader(fileInput));
if(fileInput.exists()) {
System.out.print("File has been successfully opened.\n");
readFile();
}
else
{
System.out.print("Failed to open " + inputFileName + " file");
System.out.print("\nExiting Program...");
System.exit(0);
}
System.out.print("No more data.\nGoodbye!");
input.close();
}
public static void readFile() {
Scanner output;
try {
//I get an error on this line ----> output = new Scanner ();
while(output.hasNext()) {
System.out.print("Line 1 contains these tokens:\n");
String a = output.next();
String b = output.next();
String c = output.next();
String d = output.next();
String e = output.next();
System.out.print(a + "\n" + b + "\n" + c + "\n" + d + "\n" + e + "\n");
System.out.print("Line 2 contains these tokens:\n");
String f = output.next();
String g = output.next();
String h = output.next();
String i = output.next();
String j = output.next();
String k = output.next();
System.out.print(f +"\n" + g + "\n" + h + "\n" + i + "\n" + j + "\n" + k + "\n");
}
} catch (FileNotFoundException e1) {
System.out.print("Exception is caught here");
e1.printStackTrace();
}
}
}
我使用扫描仪遇到的错误:
该行有多个标记 - 构造函数 Scanner() 是 不明确的 - 资源泄漏:“输出”永远不会
最佳答案
您正在 main 中验证您的 fileInput
,然后忽略该 File
并在 readFile 中创建一个新的
。相反,构造一个 Scanner
(错误) Scanner
并将其传递给 fileInput
。就像,
public static void readFile(Scanner output) {
// Scanner output
并传递一个Scanner
(并使用try-with-Resources
安全地关闭它)。喜欢
try (Scanner output = new Scanner(fileInput)) {
readFile(output);
}
还可以考虑读取整行并在空白处分割
while (output.hasNextLine()) { // Use if to only read one line.
System.out.println("Line contains these tokens:");
System.out.println(Arrays.toString(output.nextLine().split("\\s+")));
}
(您当前有很多硬编码的 token 变量)。
关于java - 通过调用 Java 中的方法从文件中一次读取一个字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57751849/