我有一个本地.json文件。我不希望它在服务器上,我只是希望它被包含在我的应用程序中。我试图在我的项目中直接将它粘贴到Eclipse中,但我得到了FileNotFoundException,我也尝试将它粘贴到Windows资源管理器/ Finder的工作区文件夹中,并得到相同的异常。我应该把它放在哪里?在Eclipse中包含本地.json文件Android项目
谢谢!
我有一个本地.json文件。我不希望它在服务器上,我只是希望它被包含在我的应用程序中。我试图在我的项目中直接将它粘贴到Eclipse中,但我得到了FileNotFoundException,我也尝试将它粘贴到Windows资源管理器/ Finder的工作区文件夹中,并得到相同的异常。我应该把它放在哪里?在Eclipse中包含本地.json文件Android项目
谢谢!
你应该把文件或者在你的Android项目的/assets
或/res/raw
目录。从那里,您可以通过以下任一方式检索它:Context.getResources().openRawResource(R.raw.filename)
或Context.getResources().getAssets().open("filename")
。
项目文件夹下的/资产。如果你没有,就做吧。
把文件中的资产的文件夹。 您可以使用AssetManager open(String fileName)来读取文件。
放入资产文件夹中的JSON文件,我用这样的
public static String jsonToStringFromAssetFolder(String fileName,Context context) throws IOException {
AssetManager manager = context.getAssets();
InputStream file = manager.open(fileName);
byte[] data = new byte[file.available()];
file.read(data);
file.close();
return new String(data);
}
这种方法在解析,我们可以用这样的方法:
String jsondata= jsonToStringFromAssetFolder(your_filename, your_context);
jsonFileToJavaObjectsParsing(jsondata); // json data to java objects implementation
更多信息:Prativa's Blog
我有一个非常类似的需求。我有我需要提供蓝牙打印机配置,所以我在我的资产目录包括它的标签模板文件,并将其复制到以后使用内部存储:
private static final String LABEL_TEMPLATE_FILE_NAME = "RJ_4030_4x3_labels.bin";
InputStream inputStreamOfLabelTemplate = getAssets().open(LABEL_TEMPLATE_ASSET_PATH);
labelTemplateFile = new File(getFilesDir() + LABEL_TEMPLATE_FILE_NAME);
copyInputStreamToFile(inputStreamOfLabelTemplate, labelTemplateFile);
printer.setCustomPaper(labelTemplateFile.getAbsolutePath());
// Copy an InputStream to a File.
//
private void copyInputStreamToFile(InputStream in, File file) {
try {
OutputStream out = new FileOutputStream(file);
byte[] buf = new byte[1024];
int len;
while((len=in.read(buf))>0){
out.write(buf,0,len);
}
out.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
到进一步说明何时需要使用什么:use/res/raw当您需要为您生成资源ID时。否则,你/资产。 – Matthias
谢谢先生! :-) – Magnus