java - 如何在 Android 中引用原始文件夹中的文件

标签 java android file filenotfoundexception

我只想像这样创建一个文件对象

File myImageFile = new File ("image1") ;

但它给了我 FileNotFoundException
异常 我如何引用原始文件夹中的文件

编辑: 其实我想做这样的事情

MultipartEntity multipartEntity= new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); multipartEntity.addPart("已上传", new FileBody(new File("myimage")));

最佳答案

通常,您可以通过 getResources().openRawResource(R.id._your_id) 访问文件。如果您绝对需要对它的文件引用,一种选择是将其复制到内部存储:

File file = new File(this.getFilesDir() + File.separator + "DefaultProperties.xml");
try {
        InputStream inputStream = resources.openRawResource(R.id._your_id);
        FileOutputStream fileOutputStream = new FileOutputStream(file);

        byte buf[]=new byte[1024];
        int len;
        while((len=inputStream.read(buf))>0) {
            fileOutputStream.write(buf,0,len);
        }

        fileOutputStream.close();
        inputStream.close();
    } catch (IOException e1) {}

现在您有一个文件,您可以在任何需要的地方访问它。

关于java - 如何在 Android 中引用原始文件夹中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9752417/

相关文章:

perl - 为什么 du 和 Perl 的 -s 给出了不同的文件大小值?

java - file.rename 可以替换现有文件吗?

file - 如何使用公共(public) Gradle API 创建临时文件/文件夹?

java - 考虑在你的配置中定义一个 'javax.persistence.EntityManagerFactory' 类型的 bean

java - 这个问题的最佳数据结构?

java - 属性文件字符串长度限制(JAVA)

java - Android Studio Mac Gradle 问题

java - 为什么我无法将 TextArea 中的文本与字符串进行比较?

android - 显示大图像但在 android 中共享小图像

android - GridView 中的 ImageView 之上的 ImageView