[英]Cannot Find and Read Text File on Android Studio (Java)
所以我正在使用 Android Studio 創建一個移動應用程序,它允許用戶隨機化並生成一個字符。 我正在嘗試逐行讀取字符名稱的.txt 文件,以便我可以填充一個包含所有名稱的 ArrayList。 我試圖讀取 .txt 文件的所有嘗試都沒有奏效,控制台總是聲稱該目錄和文件不存在。 我嘗試過以多種方式使用 BufferedReader、InputStreamReader 和 Scanner,如下所示:
ArrayList<String> a = new ArrayList<>();
try {
File file = new File(fileName);
InputStream in = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String curLine = br.readLine();
while (curLine != null){
a.add(curLine);
curLine = br.readLine();
}
}
catch (Exception e){
}
和...
ArrayList<String> a = new ArrayList<>();
try (
BufferedReader reader = new BufferedReader(new FileReader(fileName));
){
String curLine = reader.readLine();
for (int i = 1; i != lineNum; i++){
a.add(curLine);
curLine = reader.readLine();
}
return curLine;
}
catch (Exception e){
}
和...
ArrayList<String> a = new ArrayList<>();
try {
File myObj = new File(fileName);
System.out.println(myObj.getAbsolutePath());
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
a.add(myReader.nextLine());
}
myReader.close();
} catch (Exception e) {
}
盡管它們都無法正常工作。 我嘗試使用 file.getAbsolutePath() 顯示絕對路徑並且路徑是正確的。 我曾嘗試將文件與 src 文件夾平行放置在與 src 文件夾平行的文件夾中、res 文件夾中等等。 此外,可能需要注意的是,我通過在 FileIO class 中調用 static 方法來運行這些行,其中我將字符串文件名作為參數傳遞。 有什么我想念的嗎? When I do this in NetBeans or Eclipse I have no issue with reading from a text file, in fact some of my old projects in NetBeans have been a template for me when I'm attempting this in Android Studio.
這是我在 Android Studio 的第一個項目,所以我很可能做錯了什么,所以任何幫助將不勝感激!
注意:我知道我在提供的代碼中捕獲異常的約定效率不高,但是當我嘗試使用 FileNotFoundException 捕獲異常時,Android Studio 中的調試器由於某些奇怪的原因無法工作。
你可以試試這個:
ArrayList<String> a = new ArrayList<>();
File file = new File(filename);
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
a.add(myReader.nextLine());
}
br.close();
}
catch (IOException e) { // OR CATCH AT LEAST EXCEPTION IF IT DOESNT WORK FOR FILEIOEXCEPTION
// HERE LOG YOUR ERROR AND GIVE IT TO US
}
確保您的“文件名”不是目錄。 通過記錄一些斷言的結果來測試你的文件:
System.out.println("file exists? " + file.exists());
System.out.println("file is Dir? " + file.isDirectory());
System.out.println("file can be read? " + file.canRead());
並給我們結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.