如何在Android中的原始文件夹中打开文件 [英] How to open a file in raw folder in Android

查看:127
本文介绍了如何在Android中的原始文件夹中打开文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用MultipartEntity,我正在尝试引用原始文件夹中的文件。这里是代码:

pre $ MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart(new FormBodyPart(file,new FileBody(new File(test.txt))));

test.txt文件位于我的res / raw文件夹中。当我执行代码时,我得到以下异常:FileNotFoundException:/test.txt:打开失败:ENOENT(没有这样的文件或目录)

任何人都可以帮助我不幸的是,你不能直接创建一个 File 对象。原始文件夹。您需要将其复制或复制到您的SD卡或应用程序的缓存中。

您可以通过这种方式为您的文件检索InputStream

  InputStream in = getResources()。openRawResource(R.raw.yourfile); 

尝试{
int count = 0;
byte [] bytes = new byte [32768];
StringBuilder builder = new StringBuilder(); ((count = in.read(bytes,0,32768))> 0){
builder.append(new String(bytes,0,count));
}

in.close();
reqEntity.addPart(new FormBodyPart(file,new StringBody(builder.toString())));
} catch(IOException e){
e.printStackTrace();
}


I am usin MultipartEntity and I am trying to refer to the file in the raw folder. Here is the code:

MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart(new FormBodyPart("file", new FileBody(new File("test.txt"))));

The test.txt file is in my res/raw folder. When I execute the code I get the following exception : FileNotFoundException: /test.txt: open failed: ENOENT (No such file or directory)

Can anyone help me with this?

解决方案

Unfortunately you can not create a File object directly from the raw folder. You need to copy it or in your sdcard or inside the application`s cache.

you can retrieve the InputStream for your file this way

    InputStream in = getResources().openRawResource(R.raw.yourfile);

  try {
       int count = 0;
       byte[] bytes = new byte[32768];
       StringBuilder builder = new StringBuilder();
       while ( (count = in.read(bytes,0, 32768)) > 0) {
           builder.append(new String(bytes, 0, count));
       }

       in.close();
       reqEntity.addPart(new FormBodyPart("file", new StringBody(builder.toString())));
   } catch (IOException e) {
       e.printStackTrace();
   }

这篇关于如何在Android中的原始文件夹中打开文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆