[英]Reading files in android. how to fix bad path
我正在嘗試在android中讀取文件。 我習慣在Java中執行此操作,但在這里遇到了打開失敗的enoent(無此類文件或目錄)錯誤。 我不確定如何導入文件。 我應該將其與應用程序放在同一目錄中嗎? 現在在我的桌面上 這是我的代碼
package com.androidplot.fun;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFile {
private String path;
public ReadFile(String file_path){
path = file_path;
}
public String[] OpenFile() throws IOException{
FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader(fr);
int numberOfLines = 3;
String[ ] textData = new String[numberOfLines];
int i;
for (i=0; i < numberOfLines; i++) {
textData[ i ] = textReader.readLine();
}
textReader.close( );
return textData;
}
int readLines() throws IOException{
FileReader file_to_read = new FileReader(path);
BufferedReader bf = new BufferedReader(file_to_read);
String aLine;
int numberOfLines = 0;
while (( aLine = bf.readLine()) != null){
numberOfLines++;
}
bf.close();
return numberOfLines;
}
}
這是我一直在使用的課程。 這就是我在主程序中使用的
try{
ReadFile file = new ReadFile("/Users/jonathon/Desktop/data.txt");
String[] aryLines = file.OpenFile();
int x;
for ( x=0; x < aryLines.length; i++ ) {
System.out.println( aryLines[ i ] ) ;
}
}
catch ( IOException e ) {
System.out.println( e.getMessage() );
}
該文件將與您的應用程序捆綁在一起嗎? 如果是這樣,則應將其包括為資源。 這里是有關如何完成此操作的一些常規信息的鏈接 。
編輯:我只是看了看你的文件路徑。 在android模擬器上運行的代碼無法訪問Windows桌面。 啟動仿真器,將數據傳輸到它,然后讓應用程序嘗試從“電話”中讀取它。
該路徑無效。 如果要將其存儲在SD卡上,請從以下位置開始: Environment.getExternalStorageDirectory().getAbsolutePath();
這應該返回SD卡的根目錄,您可以將文件直接放在其中,也可以在其中創建自己的結構。 (另外,就我個人而言,除非我不想在手機無法完成的功能上進行測試,否則我不會打擾模擬器,例如不同版本的Android。我將手機插入電源並對其進行嚴格測試。是的,我懷疑Google開發人員也會這樣做...)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.