首页 > 解决方案 > 通过调用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() 未定义 - 资源泄漏:“输出”永远不会

标签: java

解决方案


您正在验证您的fileInputin main,然后忽略它FileScannerreadFile. 而是构造 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+")));
}

(您目前有很多硬编码的令牌变量)。


推荐阅读