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
Your writing code is the problem. Just use
FileWriter fos = new FileWriter(mypath);
fos.write(response);
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();
}
}
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.
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:
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;
}
}
}