【问题标题】:writing .json file and read that file in Android编写 .json 文件并在 Android 中读取该文件
【发布时间】:2012-12-22 13:23:18
【问题描述】:

我正在编写 .json 文件,我想读取该文件, 但问题是,当我尝试将整个文件作为字符串读取时,它会在每个字符之前和之后添加空格,并且只是因为额外的字符而无法读取 json。

Json 格式为

[{"description1":"The ThinkerA bronze sculpture by Auguste Rodin. It depicts a man in sober\nmeditation battling with a powerful internal struggle.","description2":"Steve JobsFounder of Apple, he is widely recognized as a charismatic pioneer of\nthe personal computer revolution.","description3":"Justin BieberBorn in 1994, the latest sensation in music industry with numerous\nawards in recent years."}]

但它给出了奇怪的响应,例如: [ { " d e s c r i p t i o n 1 " : " T h e .....

修剪多余的空间我提到了这个,但仍然没有工作: Java how to replace 2 or more spaces with single space in string and delete leading spaces only

我正在使用此代码

File folderPath = Environment.getExternalStorageDirectory();
File mypath=new File(folderPath, "description.json");
StringBuffer fileData = new StringBuffer(1000);
BufferedReader reader = null;
reader = new BufferedReader(new FileReader(mypath));
char[] buf = new char[1024];
int numRead=0;

while((numRead=reader.read(buf)) != -1)
{
    String readData = String.valueOf(buf, 0, numRead);
    fileData.append(readData);
    buf = new char[1024];
}
String response = fileData.toString();

“响应”字符串包含奇怪的响应

谁能帮帮我?

用于写入文件,我使用:

FileOutputStream fos = new FileOutputStream(mypath);
DataOutputStream dos = new DataOutputStream(fos);
dos.writeChars(response);

【问题讨论】:

  • BufferedReaderreadLine 方法。尝试使用它。
  • 你能贴出你用来写文件的代码吗?听起来您可能正在以 16 位格式编写字符。
  • 尝试打开文件,查看内容是否包含空格或不可见字符。还可以尝试记录以查看每次迭代在 numRead 和 readData 中返回的内容。这是为了缩小范围并确保问题出在阅读而不是写作。
  • @RobGThai ,我正在使用 writeChars 编写,这会导致在每个字符之前写入空格,现在我使用 writeUTF 并解决了问题。感谢大家分享他们的意见。

标签: android json string file-io


【解决方案1】:

writeChars 将每个字符写入两个字节。

http://docs.oracle.com/javase/6/docs/api/java/io/DataOutputStream.html#writeChars(java.lang.String)

http://docs.oracle.com/javase/6/docs/api/java/io/DataOutputStream.html#writeChar(int)

Writes a char to the underlying output stream as a 2-byte value, high byte first. If no exception is thrown, the counter written is incremented by 2.

【讨论】:

    【解决方案2】:

    您的编写代码是问题所在。只需使用

    FileWriter fos = new FileWriter(mypath);
    fos.write(response);
    

    【讨论】:

      【解决方案3】:

      写下面的方法写Json文件,这里params是一个文件名,mJsonResponse是一个服务器响应。

      用于将文件创建到应用程序的内存中

      public void mCreateAndSaveFile(String params, String mJsonResponse) {
          try {
              FileWriter file = new FileWriter("/data/data/" + getApplicationContext().getPackageName() + "/" + params);
              file.write(mJsonResponse);
              file.flush();
              file.close();
          } catch (IOException e) {
              e.printStackTrace();
          }
      }
      

      对于从 Json 文件中读取数据,这里params 是文件名。

      public void mReadJsonData(String params) {
          try {
              File f = new File("/data/data/" + getPackageName() + "/" + params);
              FileInputStream is = new FileInputStream(f);
              int size = is.available();
              byte[] buffer = new byte[size];
              is.read(buffer);
              is.close();
              String mResponse = new String(buffer);
          } catch (IOException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
          }
      }
      

      【讨论】:

        【解决方案4】:

        我喜欢上面的答案并编辑:我只是喜欢分享,所以我分享了可能对其他人有用的内容。

        在你的包中复制并粘贴以下类并使用:

        保存:MyJSON.saveData(context, jsonData);

        阅读:String json = MyJSON.getData(context);

        import android.content.Context;
        import android.util.Log;
        
        import java.io.File;
        import java.io.FileInputStream;
        import java.io.FileWriter;
        import java.io.IOException;
        
        /**
         * Created by Pratik.
         */
        public class MyJSON {
        
            static String fileName = "myBlog.json";
        
            public static void saveData(Context context, String mJsonResponse) {
                try {
                    FileWriter file = new FileWriter(context.getFilesDir().getPath() + "/" + fileName);
                    file.write(mJsonResponse);
                    file.flush();
                    file.close();
                } catch (IOException e) {
                    Log.e("TAG", "Error in Writing: " + e.getLocalizedMessage());
                }
            }
        
            public static String getData(Context context) {
                try {
                    File f = new File(context.getFilesDir().getPath() + "/" + fileName);
                    //check whether file exists
                    FileInputStream is = new FileInputStream(f);
                    int size = is.available();
                    byte[] buffer = new byte[size];
                    is.read(buffer);
                    is.close();
                    return new String(buffer);
                } catch (IOException e) {
                    Log.e("TAG", "Error in Reading: " + e.getLocalizedMessage());
                    return null;
                }
            }
        }
        

        【讨论】:

          猜你喜欢
          • 2018-10-11
          • 1970-01-01
          • 1970-01-01
          • 2020-05-13
          • 1970-01-01
          • 2018-02-27
          • 2011-12-18
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多