2016-04-20 72 views
1

我想導入CSV在我的SQLite數據庫在Android上,使用意圖讓用戶選擇CSV文件。'FileReader上沒有這樣的文件或目錄'錯誤 - Android

我得到上ENOENT錯誤:FileReader file = new FileReader(fileName);

該文件不存在,因爲我得到的路徑形成的意圖!

我的清單包括:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> 

我的意圖

Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
intent.setType("text/csv"); 
if (intent.resolveActivity(getPackageManager()) != null) { 
    startActivityForResult(intent, REQUEST_CVS); 

我onActivityResult(...)

if (resultCode == RESULT_OK) { 
    File myPath_CSV = new File(data.getData().toString()); 
    try { 
     myDb.importCSV(myPath_CSV); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

我importCSV(文件名)

public void importOreilles(File fileName) throws IOException { 
    Log.w(TAG, fileName.toString()); 
    FileReader file = new FileReader(fileName); // Getting an error !!! 
    BufferedReader buffer = new BufferedReader(file); 

    String line = null; 
    while ((line = buffer.readLine()) != null) { 
     String[] str = line.split(","); 
     insertOreille(str[0],str[1]); // Dealing with my database 
    } 
} 

我得到的錯誤:我使用getAbsolutePath,URI,文件試圖

W/DBAdapter: file:/storage/emulated/0/Download/Oreilles.csv 
W/System.err: java.io.FileNotFoundException: /file:/storage/emulated/0/Download/ABCDE.csv: open failed: ENOENT (No such file or directory) 

...但我堅持。

任何幫助表示讚賞。

回答

1

該文件確實存在,因爲我得到了一個意圖的路徑形式!

您決定不提供實際的「意圖」以及如何使用它。我會猜測它是ACTION_GET_CONTENT。在這種情況下,您將收回Uridata.getData())。 Use ContentResolver and openInputStream()讀入由Uri指向的內容。您可以將其包裝在InputStreamReader中,以與現有的基於Reader的代碼一起使用。

+0

剛剛添加我的意圖(Intent.ACTION_GET_CONTENT的確如此) – Tibo

+0

@Tibo:你回來的'Uri'可以有'file'或'content'方案。 'ContentResolver'和'openInputStream()'將處理這兩種情況,假設在'file'的情況下,[用戶授予您許可](https://stackoverflow.com/questions/32635704/android-permission-犯規工作偶數如果-I-有申報-它)。 – CommonsWare

+0

從你的鏈接中,我認爲我的問題是我對Uri是什麼缺乏瞭解。我將看看openInputStream。 – Tibo

相關問題