java - 通过调用Java中的方法从文件中读取,一次一个字
问题描述
目标是为我的主程序编写至少一个其他(静态)方法(函数)来调用。也许是一种处理单行的方法。然后主程序可以重复调用它,只要数据还在文件中。我无法为我的主程序创建一个函数来调用它。也许我的思维过程目前不起作用,有人可以帮忙吗?
我尝试创建一个名为 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() 未定义 - 资源泄漏:“输出”永远不会
解决方案
您正在验证您的fileInput
in main,然后忽略它File
并Scanner
在readFile
. 而是构造 aScanner
并将其传递给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+")));
}
(您目前有很多硬编码的令牌变量)。
推荐阅读
- html - TimeLine -- 单击时更改颜色
- tensorflow.js - 训练数据归一化后如何预测?
- ios - 如何将数据从父视图控制器传递到子容器视图控制器
- jquery - 引导轮播不起作用,在一列中显示图片
- javascript - 将新行动态添加到具有从 csv 文件创建的标题的数组中
- magento2 - 为什么我的 js 脚本不能在 Magento 2 类别产品中运行
- r - 文件中的错误(文件,“rt”):无法打开连接(寻找其他解决方案)
- windows - 使用批处理文件自动连接到 VNC
- vue.js - 将 json 数据作为 .scss 文件中的 sass 变量导入 Nuxt
- android - 如何检查firebase是否存在value1和value2