13

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);
4
  • 1
    BufferedReader has readLine method. Try to use it. Commented Jan 8, 2013 at 16:15
  • 1
    Could you post the code you use to write the file? Sounds like you might be writing the characters in a 16-bit format. Commented Jan 8, 2013 at 16:25
  • 1
    Try opening the file and see if the content contain space or invisible character or not. Also try logging to see what's return in numRead and readData for each iteration. This is to scope down and ensure the problem was from reading not writing. Commented Jan 8, 2013 at 17:06
  • 1
    @RobGThai , i was writing using writeChars, which it leads to write spaces before every single chars,now i m using writeUTF and problem solved. thanks all for sharing their opinions. Commented Jan 9, 2013 at 5:43

4 Answers 4

25

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();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

20

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

Comments

7

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.

Comments

1

Your writing code is the problem. Just use

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.