[英]How to solve the java.nio.file.NoSuchFileException?
我有一個名為“result.csv”的文件,我想從該文件中讀取某些數據並顯示它們。 我的 eclipse 項目文件夾本身中有該文件。 我仍然無法讀取文件。
public static void main(String [] args) {
int i=0;
String filename="result.csv";
Path pathToFile = Paths.get(filename);
try (BufferedReader br = Files.newBufferedReader(pathToFile, StandardCharsets.US_ASCII)) {
// read the first line from the text file
String line = br.readLine();
// loop until all lines are read
while (i<10) {
// use string.split to load a string array with the values from
// each line of
// the file, using a comma as the delimiter
String[] attributes = line.split(",");
double x=Double.parseDouble(attributes[8]);
double y=Double.parseDouble(attributes[9]);
System.out.println(GeoHash.withCharacterPrecision(x, y, 10));
// read next line before looping
// if end of file reached, line would be null
line = br.readLine();
i++;
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
OUTPUT:
java.nio.file.NoSuchFileException: result.csv
at sun.nio.fs.WindowsException.translateToIOException(Unknown Source)
at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
at sun.nio.fs.WindowsFileSystemProvider.newByteChannel(Unknown Source)
at java.nio.file.Files.newByteChannel(Unknown Source)
at java.nio.file.Files.newByteChannel(Unknown Source)
at java.nio.file.spi.FileSystemProvider.newInputStream(Unknown Source)
at java.nio.file.Files.newInputStream(Unknown Source)
at java.nio.file.Files.newBufferedReader(Unknown Source)
at com.uvce.cse.searchiot.geohash.TestGeoHash.main(TestGeoHash.java:19)
誰能指出我到底錯過了什么? 我該如何克服這種方法或這種方法的任何替代方法?
問題是您在應用程序啟動時的默認目錄不是您認為的那樣。 在創建路徑之后,嘗試將以下行添加到您的代碼中:
public static void main(String [] args) {
int i=0;
String filename="result.csv";
Path pathToFile = Paths.get(filename);
System.out.println(pathToFile.toAbsolutePath());
這樣,您將准確地看到它正在尋找文件的位置。
如何修復它是您的決定。 您可以使用完整路徑規范而不僅僅是文件名,或者將文件名放在特殊的“資源”目錄中並使用相對路徑引用它,或者將文件移動到默認目錄所在的任何位置。
如果您的file("result.csv")
在 src 目錄中,您應該使用“src/result.csv”而不是“result.csv” 。
問題在於 java 無法在項目文件夾中找到“result.csv”文件。 因此,嘗試使用文件的完全限定路徑,例如 Path 變量中的C:\\your_folder\\project\\result.csv
。 另外我認為最好像這樣使用bufferedreader: BufferedReader br = new BufferedReader(new FileReader(insert here the String in which is defined the path to the file));
在此處檢查 BufferedReader 的使用
如果您是 MacOSX 用戶,請手動輸入文件路徑,而不是從“獲取信息”中復制。 如果你從“獲取信息”中復制它,你會得到這樣的東西: /Users/username<200e><2068><2068>/Desktop<2069>/source.txt
我遇到了由 Windows 文件路徑上的轉義字符引起的相同錯誤。 例如,我的應用程序正在尋找“ C:\\Users\\david\\my%20folder%20name\\source.txt
”,而實際路徑是“ C:\\Users\\david\\my folder name\\source.txt
”。
這里不舍棄所有可能的解決方案,當您在 Windows 環境下運行 Android Studio 並使用非 NFTS 格式的外部硬盤驅動器上的項目目錄時,也會出現此錯誤。 ]
如果是這種情況,只需將您的項目移動到主硬盤 (NTFS) 並再次重新加載項目,這次是從主硬盤文件夾路徑。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.