编写.json文件并在Android中读取该文件

时间:2013-01-08 16:11:44

标签: android json string file-io

我正在写.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 1 1”:“T h e .....

修剪额外的空间我指的是这个,但是stil没有用: 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();

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

所以有人可以帮助我吗?

写入文件,我使用:

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

4 个答案:

答案 0 :(得分:22)

写下以下写入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();
    }
}

答案 1 :(得分:17)

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

在包中复制并粘贴以下类,并使用如下:

保存: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;
        }
    }
}

答案 2 :(得分:3)

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.

答案 3 :(得分:0)

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

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