2016-03-04 296 views
0

我試圖讀取我的SDCARD上的CSS文件的內容。使用此路徑檢索SD卡上的文件:「/ document/primary:...」

我選擇從操作的文件:

Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
        intent.setType("text/css"); 
        startActivityForResult(intent, 1); 

這裏我搶路徑:

public void onActivityResult(int requestCode, int resultCode, Intent data) { 
      SharedPreferences sharedPref = PreferenceManager 
        .getDefaultSharedPreferences(getActivity().getApplicationContext()); 
      SharedPreferences.Editor editor = sharedPref.edit(); 

      if (requestCode == 1) { 
       if(resultCode == Activity.RESULT_OK){ 
        Log.d("FilePicker", data.getData().toString()); 
        editor.putString("custom_style_file", data.getData().getPath()); 
        editor.commit(); 


       } 
       if (resultCode == Activity.RESULT_CANCELED) { 
        //Write your code if there's no result 
       } 
      } 
     } 

我得到以下路徑/document/primary:CustomCSS/myCustom.css

然後我嘗試閱讀具有此功能的文件內容:

public static String readFromSDcard(String path) { 
     File sdcard = Environment.getExternalStorageDirectory(); 

     //Get the text file 
     File file = new File(sdcard, path); 

     //Read text from file 
     StringBuilder text = new StringBuilder(); 

     try { 
      BufferedReader br = new BufferedReader(new FileReader(file)); 
      String line; 

      while ((line = br.readLine()) != null) { 
       text.append(line); 
      } 
      br.close(); 
     } 
     catch (IOException e) { 
      //You'll need to add proper error handling here 
     } 

     Log.d("Read from file", text.toString()); 
     return text.toString(); 
    } 

該函數什麼也沒有返回,我不知道我在這裏做錯了什麼。

+0

發佈您的logcat –

回答

0

確保您有讀取存儲許可清單檔案中的

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> 
1
//You'll need to add proper error handling here 

如果你這樣做,你會看到爲什麼你的函數返回什麼。

例如:

text.append("IOException: " + e.getMessage() + "\n"); 

您的路徑:

/document/primary:CustomCSS/myCustom.css 

這不是一個文件syctem路徑,但內容提供商路徑。

所以得到一個內容解析器,然後讓它打開文件的輸入流。之後,您可以使用常用的代碼來閱讀內容。

Google for getContentResolver()。openInputStream()。

+0

您是否有使用contect解析器的例子?我似乎無法找到任何例子。 – dasmikko

+0

如果您只將它複製到您的瀏覽器中,您已經有幾次搜索。選擇它們並獲得示例的世界。你甚至會看到它與'data.getData()'相結合。還有什麼願望? – greenapps