微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我只想创建一个这样的File对象

File myImageFile = new File(“image1”);

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

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

multipartentity multipartentity = new multipartentity(HttpMultipartMode.broWSER_COMPATIBLE);
multipartentity.addPart(“uploaded”,new FileBody(new File(“myimage”)));

解决方法

这里有2个功能.一个从RAW读取,一个从资产中读取
/**
 * Method to read in a text file placed in the res/raw directory of the
 * application. The method reads in all lines of the file sequentially.
 */

public static void readRaw(Context ctx,int res_id) {

    InputStream is = ctx.getResources().openRawResource(res_id);
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr,8192); // 2nd arg is buffer
                                                        // size

    // More efficient (less readable) implementation of above is the
    // composite expression
    /*
     * BufferedReader br = new BufferedReader(new InputStreamReader(
     * this.getResources().openRawResource(R.raw.textfile)),8192);
     */

    try {
        String test;
        while (true) {
            test = br.readLine();
            // readLine() returns null if no more lines in the file
            if (test == null)
                break;
        }
        isr.close();
        is.close();
        br.close();
    } catch (IOException e) {
        e.printstacktrace();
    }

}

和Assets文件

/**
 * Read a file from assets
 * 
 * @return the string from assets
 */

public static String getQuestions(Context ctx,String file_name) {

    AssetManager assetManager = ctx.getAssets();
    ByteArrayOutputStream outputStream = null;
    InputStream inputStream = null;
    try {
        inputStream = assetManager.open(file_name);
        outputStream = new ByteArrayOutputStream();
        byte buf[] = new byte[1024];
        int len;
        try {
            while ((len = inputStream.read(buf)) != -1) {
                outputStream.write(buf,len);
            }
            outputStream.close();
            inputStream.close();
        } catch (IOException e) {
        }
    } catch (IOException e) {
    }
    return outputStream.toString();

}

原文地址:https://www.jb51.cc/android/123096.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐