在Android外部存储中打开文件,并读取JSON字符串



我正在尝试从Android设备的下载文件夹中保存的文件中获取JSON字符串。现在,我可以使用此处提供的FileBrowser来获得通往此的路。

我试图使用此处给出的IDION打开文件并读取字符串。(显然,Android不使用Java 7?我无法使用此问题中的答案,我发现的唯一文件类位于Android.provider.mediastore下)

在任何情况下,我都会使用该问题中的成语获得(有点)JSON字符串。问题是我不能将输出与gson一起使用(错误:预期begin_object,但在第1行1列是字符串)

我怀疑这是因为我从文件回到字符串函数看起来像这样:

����z������9>{
   "chEqEnable": [
   [
      true,
      true,
... etc ...

也偶尔会呈现出布尔值,例如:

z������      true,

而不是

true,

处理Android和外部存储时,是否有更好的方法来获取我的文件并从中读取JSON字符串,免费差?

供参考,这是我对另一个问题的成语的实现:

public static String file2String(String filePath) throws IOException
{
    StringBuilder stringBuilder = new StringBuilder();
    BufferedReader reader = new BufferedReader(new FileReader(filePath));
    String line = null;
    try{
        while( (line = reader.readLine()) != null)
        {
            stringBuilder.append(line);
        }
    } finally {
        reader.close();
    }
    String returnStr = stringBuilder.toString();
    return returnStr;
}

当我将文件写入外部存储时,我会使用此

public static String ExportTuning(Context context, String fileName, String json)
    {
        File path;
        if(fileName.contains(".rfts")) {
            path = GetDocumentsPath(fileName);
        } else {
            path = GetDocumentsPath(fileName+".rfts");
        }
        try {
            FileOutputStream fileOut = new FileOutputStream(path);
            ObjectOutput strOut = new ObjectOutputStream(fileOut);
            strOut.writeUTF(json);
//            strOut.writeChars(json); // this just causes a ton of gibberish when I read the file back
            strOut.close();
            fileOut.close();
            String[] paths = new String[]{path.getAbsolutePath()};
            MediaScannerConnection.scanFile(context, paths, null, null);
            return "Save Successful";
        }
        catch(java.io.IOException e) {
            return e.getMessage();
        }
    }

处理Android和外部存储时,是否有更好的方法来获取我的文件并从中读取JSON字符串,免费差?

您的主要问题在于ExportTuning()方法。您不是在写JSON。您正在将Java对象写入ObjectOutputStream。如果您想编写JSON,请摆脱ObjectOutputStream并使用文字而不是对象(例如PrintWriter)的内容。请注意,您可以使用您喜欢的文本编辑器或cat或其他任何内容检查JSON文件,以查看它是否包含您的期望。

以稍后解析JSON,删除所有读取代码,创建Reader对象(例如InputStreamReader),然后将其传递给fromJson()

最新更新