【问题标题】:Include local .json file in Eclipse Android project在 Eclipse Android 项目中包含本地 .json 文件
【发布时间】:2011-08-18 14:47:50
【问题描述】:

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

谢谢!

【问题讨论】:

    标签: java android eclipse json


    【解决方案1】:

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

    【讨论】:

    • 进一步阐明何时使用什么:当您需要为您生成资源 ID 时使用 /res/raw。否则,你 /assets。
    【解决方案2】:

    把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's Blog

    【讨论】:

    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

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

      【讨论】:

        【解决方案5】:

        将资产复制到本地存储

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-10-06
          • 1970-01-01
          • 2012-01-07
          • 1970-01-01
          • 2011-09-15
          • 2016-11-17
          • 2016-12-22
          • 2011-01-04
          相关资源
          最近更新 更多