Sunil Lohar
Sunil Lohar

Reputation: 2242

writing .json file and read that file in Android

i m writing .json file and i want to read that file, but the problem is, when i try to read whole file as string it adds the space before and after every character and just because of extra chars it couldn't read json.

the Json format is

[{"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."}]

but it gives weired response like: [ { " d e s c r i p t i o n 1 " : " T h e .....

to trim extra spaces i refered to this, but stil didnt work: Java how to replace 2 or more spaces with single space in string and delete leading spaces only

i m using this code

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

the "response" string contains weird response

so can anyone help me ?

for writing into file ,i m using :

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

Upvotes: 13

Views: 34462

Answers (4)

Pratik Butani
Pratik Butani

Reputation: 62411

I like above answer and edited: I just love to share so i have shared that may be useful to others.

Copy and Paste following class in your package and use like:

Save: MyJSON.saveData(context, jsonData);

Read: 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;
        }
    }
}

Upvotes: 20

Dipak Keshariya
Dipak Keshariya

Reputation: 22291

Write below method for Write Json File, Here params is a File Name and mJsonResponse is a Server Response.

For Create Files into Internal Memory of Application

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

For Read Data From Json File, Here params is File Name.

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

Upvotes: 25

auselen
auselen

Reputation: 28087

writeChars writes each character as two bytes.

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.

Upvotes: 7

Henry
Henry

Reputation: 43728

Your writing code is the problem. Just use

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

Upvotes: 1

Related Questions