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);
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();
}
}
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;
}
}
}
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.
Your writing code is the problem. Just use
FileWriter fos = new FileWriter(mypath);
fos.write(response);
Related
I have json response in string datatype. I want to save this text to sharedpreferences but it neither gives me error nor save it to sharedpreferences.
but when I try to retrieve it gives me empty value and null pointer exception if I fetch its length. MY JSON REPONE is at
http://www.professionalhub.pk/recipe/webServices/recipe1.php
Use this class for your purpose with files ! Hope it will help you !
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;
}
}
}
I have three strings which write in to list.txt file with this code
String filepath = Environment.getExternalStorageDirectory().getPath();
String filename=filepath+"/" + FOLDER + "/" + "list.txt" ;
FileOutputStream fop = null;
File file = null;
try {
file =new File(filename);
fop=new FileOutputStream(file,true);
// if file doesn't exists, then create it
if (!file.exists()) {
file.createNewFile();
}
filecontent=filecontent+ System.getProperty ("line.separator");
// get the content in bytes
byte[] contentInBytes = filecontent.getBytes();
fop.write(contentInBytes);
fop.flush();
fop.close();
} catch (IOException e) {
e.printStackTrace();
}
The file output detail is
abc.mp3
cde.mp3
edf.mp3
Now, I want to read the detail in list.txt. I used below code but the output only has
cde.mp3
edf.mp3
What is happen with my code? I don't know why data abc.mp3 disappear.
ArrayList<String> data;
try {
String filepath = Environment.getExternalStorageDirectory().getPath();
String filename=filepath+"/" + FOLDER + "/" + "list.txt" ;
BufferedReader in = new BufferedReader(new FileReader(filename));
String audio_name;
audio_name = in.readLine();
data = new ArrayList<String>();
while ((audio_name = in.readLine()) != null) {
data.add(audio_name);
}
in.close();
} catch (IOException e) {
System.out.println("File Read Error");
}
for (int i=0;i<data.size();i++)
{
Log.d("D",String.valueOf(data.get(i)));
}
The first instance of audio_name = in.readLine() would read the first line abc.mp3 but the input is not used. Thus first line read by your while loop and stored in data would be cde.mp3. You should remove the first instance of audio_name = in.readLine().
audio_name = in.readLine();
data = new ArrayList<String>();
You read your first line into your audio_name variable, but you never add it to the list, so that's why it's "missing".
So, my app receives a large xml from a soap server. I wish to save this in a file, for later use. I managed to do this, and to read the file. BUT the result (after reading) is a garbled xml! A large portion of text (412 characters) from the latter part of the xml is copied and pasted at the end of my xml, and I can't figure out why this is happening.
I have tried 2 ways to write the file and 2 ways to read the file, no dice! (will post code below) Note: xml is large 5000-20000 characters, so I used methods to keep eclipse from returning out of memory error.
BOTTOM LINE:
-input xml file is correct
-output xml file is incorrect
-tried 2 save methods
-tried 2 read methods
-wtf?!
save code 1:
InputStream is = new ByteArrayInputStream(string.getBytes());
FileOutputStream fos = ctx.openFileOutput(filename, Context.MODE_PRIVATE);
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer))>0){
fos.write(buffer, 0, length);
}
fos.flush();
fos.close();
is.close();
save code 2 :
InputStream is = new ByteArrayInputStream(string.getBytes());
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
FileOutputStream fos = ctx.openFileOutput(filename, Context.MODE_PRIVATE);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
Log.e("stuff is good", "line: "+line);
sb.append(line);
if (sb.toString().length() > 10000) {
fos.write(sb.toString().getBytes());
fos.flush();
sb = new StringBuilder();
}
}
fos.write(sb.toString().getBytes());
fos.flush();
is.close();
fos.close();
read code 1:
FileInputStream fis = openFileInput("caca");
int c;
StringBuilder fileContent = new StringBuilder();
while((c=fis.read())!=-1)
{
fileContent.append((char)c);
}
fis.close();
Log.e("TEST TEST", "XML length = "
+String.valueOf(fileContent.length()) );
Log.e("TEST TEST", "XML = "
+fileContent );
read code 2 :
FileInputStream fis;
fis = openFileInput("caca");
StringBuffer fileContent = new StringBuffer("");
byte[] buffer = new byte[1024];
int i =1;
while (fis.read(buffer) != -1) {
fileContent.append(new String(buffer));
Log.v("TEST"+ String.valueOf(i), new String(buffer) );
i++;
}
Log.e("TEST TEST", "XML length = "
+String.valueOf(fileContent.length()) );
Log.e("TEST TEST", "XML = "
+fileContent );
save to file code :
File myFile = new File("/sdcard/mysdfile.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append(fileContent);
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Done writing SD 'mysdfile.txt'",
Toast.LENGTH_SHORT).show();
Sorry for the long post, but after 3 days, I'm at my wits end. Any input would be nice, thank you!
I prefer to use Apache Commons IO for this:
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url + id);
try {
HttpResponse response = client.execute(httpGet);
InputStream content = response.getEntity().getContent();
StringWriter writer = new StringWriter();
IOUtils.copy(content, writer, "utf-8");
return writer.toString();
} catch (ClientProtocolException e) {
Log.e(tag, "client problem:" + e.getMessage());
throw new RuntimeException("client problem",e);
} catch (IOException e) {
Log.e(tag, "IO problem:" + e.getMessage());
throw new RuntimeException("IO problem",e);
}
Then just write out the string as usual.
ok.... I fixed it , I have no idea why it works.
save code:
public static void Save(String filename, String string,
Context ctx) {
Log.e("stuff is good", "xml length b4 save= "+String.valueOf(string.length()));
try {
FileOutputStream fOut = ctx.openFileOutput(filename, Context.MODE_PRIVATE);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append(Login.messagesXmlDump);
myOutWriter.close();
fOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
read code:
Save("LOL", messagesXmlDump, getApplicationContext());
try {
FileInputStream fis = openFileInput("LOL");
int c;
StringBuilder fileContent = new StringBuilder();
while((c=fis.read())!=-1)
{
fileContent.append((char)c);
}
fis.close();
Managed to write/read a 70k characters long xml. Maybe that recursive method of saving it wasn't the best idea. Think I over-complicated a simple matter.
Sorry for wasting your time :(
I need to copy a PNG file form res.raw my App's private internal memory. This is code I am using. The resulting file appears to be corrupt in that BitmapFactory.decodeFile() returns null. The same file, if placed on the SD Card decodes just fine. Here is the code that I am using.
private void loadGraphics(){
InputStream inputStream = BasicContext.getResources().openRawResource(R.raw.galaxy);
InputStreamReader inputreader = new InputStreamReader(inputStream);
BufferedReader buffreader = new BufferedReader(inputreader, 8192);
int Byte = 0;
FileWriter writer = null;
String PathA = "/sdcard/rfo-basic/data/Galaxy1.png";
try {
writer = new FileWriter(PathA);
do {
Byte = buffreader.read();
{writer.write(Byte);}
} while (Byte != -1);
} catch (IOException e) {
Log.v(Basic.LOGTAG, " " + Basic.CLASSTAG + " I/O Exception 2 ");
}
finally {
if (writer != null) {
try {
writer.flush();
writer.close();
} catch (IOException e) {
Log.v(Basic.LOGTAG, " " + Basic.CLASSTAG + " I/O Exception 4 ");
}
}
}
}
How to create a file, write data into it and read data from it on Android? If possible provide a code snippet.
I used the following code to create a temporary file for writing bytes. And its working fine.
File file = new File(Environment.getExternalStorageDirectory() + "/" + File.separator + "test.txt");
file.createNewFile();
byte[] data1={1,1,0,0};
//write the bytes in file
if(file.exists())
{
OutputStream fo = new FileOutputStream(file);
fo.write(data1);
fo.close();
System.out.println("file created: "+file);
}
//deleting the file
file.delete();
System.out.println("file deleted");
From here: http://www.anddev.org/working_with_files-t115.html
//Writing a file...
try {
// catches IOException below
final String TESTSTRING = new String("Hello Android");
/* We have to use the openFileOutput()-method
* the ActivityContext provides, to
* protect your file from others and
* This is done for security-reasons.
* We chose MODE_WORLD_READABLE, because
* we have nothing to hide in our file */
FileOutputStream fOut = openFileOutput("samplefile.txt",
MODE_PRIVATE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
// Write the string to the file
osw.write(TESTSTRING);
/* ensure that everything is
* really written out and close */
osw.flush();
osw.close();
//Reading the file back...
/* We have to use the openFileInput()-method
* the ActivityContext provides.
* Again for security reasons with
* openFileInput(...) */
FileInputStream fIn = openFileInput("samplefile.txt");
InputStreamReader isr = new InputStreamReader(fIn);
/* Prepare a char-Array that will
* hold the chars we read back in. */
char[] inputBuffer = new char[TESTSTRING.length()];
// Fill the Buffer with data from the file
isr.read(inputBuffer);
// Transform the chars to a String
String readString = new String(inputBuffer);
// Check if we read back the same chars that we had written out
boolean isTheSame = TESTSTRING.equals(readString);
Log.i("File Reading stuff", "success = " + isTheSame);
} catch (IOException ioe)
{ioe.printStackTrace();}
I decided to write a class from this thread that may be helpful to others. Note that this is currently intended to write in the "files" directory only (e.g. does not write to "sdcard" paths).
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import android.content.Context;
public class AndroidFileFunctions {
public static String getFileValue(String fileName, Context context) {
try {
StringBuffer outStringBuf = new StringBuffer();
String inputLine = "";
/*
* We have to use the openFileInput()-method the ActivityContext
* provides. Again for security reasons with openFileInput(...)
*/
FileInputStream fIn = context.openFileInput(fileName);
InputStreamReader isr = new InputStreamReader(fIn);
BufferedReader inBuff = new BufferedReader(isr);
while ((inputLine = inBuff.readLine()) != null) {
outStringBuf.append(inputLine);
outStringBuf.append("\n");
}
inBuff.close();
return outStringBuf.toString();
} catch (IOException e) {
return null;
}
}
public static boolean appendFileValue(String fileName, String value,
Context context) {
return writeToFile(fileName, value, context, Context.MODE_APPEND);
}
public static boolean setFileValue(String fileName, String value,
Context context) {
return writeToFile(fileName, value, context,
Context.MODE_WORLD_READABLE);
}
public static boolean writeToFile(String fileName, String value,
Context context, int writeOrAppendMode) {
// just make sure it's one of the modes we support
if (writeOrAppendMode != Context.MODE_WORLD_READABLE
&& writeOrAppendMode != Context.MODE_WORLD_WRITEABLE
&& writeOrAppendMode != Context.MODE_APPEND) {
return false;
}
try {
/*
* We have to use the openFileOutput()-method the ActivityContext
* provides, to protect your file from others and This is done for
* security-reasons. We chose MODE_WORLD_READABLE, because we have
* nothing to hide in our file
*/
FileOutputStream fOut = context.openFileOutput(fileName,
writeOrAppendMode);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
// Write the string to the file
osw.write(value);
// save and close
osw.flush();
osw.close();
} catch (IOException e) {
return false;
}
return true;
}
public static void deleteFile(String fileName, Context context) {
context.deleteFile(fileName);
}
}
Write to a file test.txt:
String filepath ="/mnt/sdcard/test.txt";
FileOutputStream fos = null;
try {
fos = new FileOutputStream(filepath);
byte[] buffer = "This will be writtent in test.txt".getBytes();
fos.write(buffer, 0, buffer.length);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(fos != null)
fos.close();
}
Read from file test.txt:
String filepath ="/mnt/sdcard/test.txt";
FileInputStream fis = null;
try {
fis = new FileInputStream(filepath);
int length = (int) new File(filepath).length();
byte[] buffer = new byte[length];
fis.read(buffer, 0, length);
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(fis != null)
fis.close();
}
Note: don't forget to add these two permission in AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />