簡體   English   中英

在Eclipse(Java)中無法使用Scanner讀取txt文件

[英]Can't read txt file with Scanner in Eclipse (Java)

對於在Eclipse (jre1.8.0_181)中正在處理的項目,我很難讀取.txt文件(words.txt)。 我有一個word.txt的副本

String wordsPath = "C:\\Users\\Administrator\\Documents\\words.txt";

以及項目目錄本身(我嘗試定義多種方式):

String workingDir = System.getProperty("user.dir");
String wordsPath2 = workingDir.concat("\\words.txt");
String wordsPath3 = new File("").getAbsolutePath().concat("\\words.txt");

但是,當我嘗試建立filein

Scanner filein = new Scanner(new File(wordsPath));
filein = new Scanner(new File(wordsPath2));
filein = new Scanner(new File(wordsPath3));

我在所有嘗試中都得到FileNotFoundException 有人對此有見識嗎? 我知道文件在那里。 我還想念什么? 我相信我也有正確的導入( import java.io.File;import java.util.Scanner; )。 我瀏覽了許多類似的問題,沒有運氣。 非常感謝!

可以正確讀取以下程序中的兩個文件。 比較並查看您是否做錯了什么。

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReadFile
{
  public static void main(String[] args)
  {
    try
    {
      Scanner scanner = new Scanner(new File("words.txt"));
      System.out.println(scanner.nextLine());
      System.out.println(scanner.nextLine());

      Scanner scanner2 = new Scanner(new File("C:\\Users\\prasad.karunagoda\\words2.txt"));
      System.out.println(scanner2.nextLine());
      System.out.println(scanner2.nextLine());
    }
    catch (FileNotFoundException ex)
    {
      ex.printStackTrace();
    }
  }
}

暫無
暫無

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

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