2011-08-18 72 views
14

我有一个本地.json文件。我不希望它在服务器上,我只是希望它被包含在我的应用程序中。我试图在我的项目中直接将它粘贴到Eclipse中,但我得到了FileNotFoundException,我也尝试将它粘贴到Windows资源管理器/ Finder的工作区文件夹中,并得到相同的异常。我应该把它放在哪里?在Eclipse中包含本地.json文件Android项目

谢谢!

回答

30

你应该把文件或者在你的Android项目的/assets/res/raw目录。从那里,您可以通过以下任一方式检索它:Context.getResources().openRawResource(R.raw.filename)Context.getResources().getAssets().open("filename")

+8

到进一步说明何时需要使用什么:use/res/raw当您需要为您生成资源ID时。否则,你/资产。 – Matthias

+0

谢谢先生! :-) – Magnus

0

项目文件夹下的/资产。如果你没有,就做吧。

4

把文件中的资产的文件夹。 您可以使用AssetManager open(String fileName)来读取文件。

10

放入资产文件夹中的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

+1

你的答案是非常相似的一个在这个环节http://prativas.wordpress.com/category/android/part-1-retrieving-a-json-file/ – Prativa

+0

+1在您的博客你的贡献关于json。 –

+0

@ Subra - 感谢您的参考 – Prativa

0

将资产复制到本地存储

我有一个非常类似的需求。我有我需要提供蓝牙打印机配置,所以我在我的资产目录包括它的标签模板文件,并将其复制到以后使用内部存储:

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()); 

copyInputStreamToFile功能

// 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(); 
    } 
} 
相关问题