繁体   English   中英

在Eclipse Android项目中包含本地.json文件

[英]Include local .json file in Eclipse Android project

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

谢谢!

您应该将文件放在Android项目的/assets/res/raw目录中。 从那里,您可以使用以下任一方法检索它: Context.getResources().openRawResource(R.raw.filename)Context.getResources().getAssets().open("filename")

把json文件放在assets文件夹中,我已经像这样使用了这个方法

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的博客

将文件放在assets文件夹中。 您可以使用AssetManager open(String fileName)来读取文件。

将资产复制到本地存储

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

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

在项目文件夹中的/ assets下。 如果你没有,那就去做吧。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM