簡體   English   中英

通過調用Java中的方法從文件中一次讀取一個單詞

[英]Reading from a file, one word at a time by calling a method in 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()未定義-資源泄漏:從不輸出'output'

您正在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+")));
}

(您目前有很多硬編碼的令牌變量)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM