问题描述
我只是想创建这样一个文件对象
I just want to create a File object like this
文件myImageFile =新的文件(此搜索);
但它给我的异常 FileNotFoundException异常
如何引用文件在我的原始文件夹
but it is giving me exception of FileNotFoundException
How can i reference a file inside my raw Folder
编辑:其实我想要做这样的事情
Actually i wanted to do something like this
MultipartEntity multipartEntity =新MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); multipartEntity.addPart(上载,新FileBody(新文件(MYIMAGE)));
MultipartEntity multipartEntity= new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); multipartEntity.addPart("uploaded", new FileBody(new File("myimage")));
推荐答案
这里有2个功能。一位来自RAW读取和一名来自资产
here are 2 functions. one to read from RAW and one from the Assets
/**
* 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();
}
}
和从资产文件夹
/**
* 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, 0, len);
}
outputStream.close();
inputStream.close();
} catch (IOException e) {
}
} catch (IOException e) {
}
return outputStream.toString();
}
这篇关于如何引用原始文件夹中的Android文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!