【问题标题】:File Object is Not Getting Created未创建文件对象
【发布时间】:2017-11-30 20:39:02
【问题描述】:

我正在向用户提供文件浏览器以选择文件。在 onActivityResult 我得到的文件路径为 - /file/sdcard/Android/data/com.coca_cola.android.conferenceapp/cache/Conference/export.txt。当我尝试在此创建文件对象时,我无法创建。当我删除 /file/ 并在 sdcard/Android/data/com.coca_cola.android.conferenceapp/cache/Conference/export.txt 上创建文件对象时,它会被创建。但我不能硬编码从文件路径中删除 /file/ ,因为在其他设备上它将提供一些其他路径。下面是代码

private void readContactFromFile(String path) {
    StringBuilder text = new StringBuilder();
    try {
        String st = "/file/sdcard/Android/data/com.coca_cola.android.conferenceapp/cache/Conference/export.txt";
        File file = new File(st);
        if (file.exists()) {
            Log.v("TTT", "file exist");
        }
        Log.v("TTT", file.toString());
        BufferedReader br = new BufferedReader(new FileReader(file));
        String line;
        while ((line = br.readLine()) != null) {
            text.append(line);
            Log.i("Test", "text : " + text + " : end");
            text.append('\n');
        }
        br.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

我正在获取 OnActivityResult 的路径

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (resultCode == RESULT_OK) {

        switch (requestCode) {

            case REQUEST_PICK_FILE:
                Uri uri = data.getData();
                String path = data.getData().getPath();
                Log.v("PATH", path);

                readContactFromFile(path);
                break;
        }
    }
}

这就是我要求打开文件浏览器的方式

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("*/*");      //all files
    //intent.setType("text/xml");   //XML file only
    intent.addCategory(Intent.CATEGORY_OPENABLE);

    try {
        startActivityForResult(Intent.createChooser(intent, "Select a File to Upload"), REQUEST_PICK_FILE);
    } catch (android.content.ActivityNotFoundException ex) {
        // Potentially direct the user to the Market with a Dialog
        Toast.makeText(this, "Please install a File Manager.", Toast.LENGTH_SHORT).show();
    }

如何获得完美路径或如何消除此问题? 提前致谢

【问题讨论】:

  • 请编辑您的问题并发布触发此onActivityResult() 呼叫的startActivityForResult() 呼叫。
  • 我做到了。请签入编辑

标签: android android-file


【解决方案1】:

由于不同设备上的路径不同,您应该使用框架api为您检索合适的路径。

看看Environment class

【讨论】:

  • 我需要做什么?
【解决方案2】:

使用环境类获取路径,而不是使用硬编码的字符串路径

File file=new File(String.valueOf(Environment.getExternalStorageDirectory())+"YOUR_REQUIRED_FILE_PATH");

它不会因设备而异。 希望这会有所帮助:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-25
    • 2015-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多