4

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?

4

2 回答 2

9

不幸的是,您不能File直接从原始文件夹创建对象。您需要将其复制到 SD 卡中或应用程序的缓存中。

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

    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();
   }
于 2013-05-24T18:31:47.503 回答
3

您可以将文件放在 /res/raw 目录中,该文件将被索引并且可以通过 R 文件中的 id 访问:

InputStream is = getResources().openRawResource(R.raw.test);
System.out.println(is);
于 2013-05-24T18:52:23.267 回答