Saving/reading large xml string to/from file - android

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 :(

Related

how to delete a file from android studio code

I create and manage file from android application with this code but what I want then its to delete it.
This is the code how I write and read it:
private String readDataFromString()
{
try{
FileInputStream fis = this.openFileInput("encryptedNotePad.txt");
InputStreamReader isr = new InputStreamReader(fis);
char[] inputBuffer = new char[100];
String s = "";
int charRead;
while((charRead = isr.read(inputBuffer)) > 0){
// Convertimos los char a String
String readString = String.copyValueOf(inputBuffer, 0, charRead);
s += readString;
inputBuffer = new char[100];
}
isr.close();
return s;
}catch (IOException ex){
ex.printStackTrace();
}
return null;
}
private void writeDataToString (String data) throws FileNotFoundException {
try{
//FileOutputStream fos = openFileOutput("encryptedNotePad.txt", MODE_PRIVATE);
FileOutputStream fos = this.openFileOutput("encryptedNotePad.txt", MODE_PRIVATE);
OutputStreamWriter osw = new OutputStreamWriter(fos);
// Escribimos el String en el archivo
osw.write(data);
osw.flush();
osw.close();
}catch (IOException ex){
ex.printStackTrace();
}
}
How Can I delete it?
I found this:
File file = new File(selectedFilePath);
boolean deleted = file.delete();
But, I dont know the file path.Whats the file path?
But, I dont know the file path.Whats the file path?
Path means the file's path where you can get access to it or doing stuff on it.
I believe in your case, it will be:
encryptedNotePad.txt
Like you used it already:
FileOutputStream fos = this.openFileOutput("encryptedNotePad.txt", MODE_PRIVATE);
So if you give the path to the following code, it should work fine I hope:
File file = new File("encryptedNotePad.txt");
boolean deleted = file.delete();

Reading a file in android

I am writing an android app where I am trying to read from a data base that I added in assets folder in main folder. But I am get an error file not found exception
public File database = new File("/assets/GeoIP2.mmdb");
PS : It's a database file not a text file.
This is the proper way to read files from assets folder
AssetManager am = context.getAssets();
InputStream is = am.open("GeoIP2.mmdb");
you can try this below code its working 100%
private String readFromFile(String name) {
String ret = "";
try {
InputStream inputStream = getAssets().open(name + ".txt");
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = bufferedReader.readLine()) != null) {
stringBuilder.append(receiveString);
stringBuilder.append("\n");
}
inputStream.close();
ret = stringBuilder.toString();
}
} catch (FileNotFoundException e) {
Log.e(TAG, "File not found: " + e.toString());
} catch (IOException e) {
Log.e(TAG, "Can not read file: " + e.toString());
}
return ret;
}
just change the format of your file instead of .txt
InputStream is = getAssets().open("thirukkuralxml.xml");
try{
String verify, putData;
File file = new File("file.txt");
file.createNewFile();
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("Some text here for a reason");
bw.flush();
bw.close();
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
while( (verify=br.readLine()) != null ){ //***editted
//**deleted**verify = br.readLine();**
if(verify != null){ //***edited
putData = verify.replaceAll("here", "there");
bw.write(putData);
}
}
br.close();
}catch(IOException e){
e.printStackTrace();
}

Making a temp file and rename it on Android internal memory

I have a .txt file which contains let's say
1;2;3;4;5
a;b;c;d;e
A;B;C;D;E
And I would like to remove the line which begins with "a"
I made a copy of the file and write there the lines unless the line equals the lineToRemove
So here what's I did but the file hasn't change
String path = "playlist.txt"
String lineToRemove = "a";
public boolean removeLineFromFile(String lineToRemove) {
try {
File inFile = new File(path);
//Creating a temp file
File tempFile = new File(inFile.getAbsolutePath()+".tmp");
FileInputStream fIn = openFileInput(path);
InputStreamReader isr = new InputStreamReader(fIn);
BufferedReader br = new BufferedReader(isr);
FileOutputStream fOut_temp = openFileOutput(path +".tmp", Context.MODE_APPEND);
OutputStreamWriter osw_temp = new OutputStreamWriter(fOut_temp);
osw_temp.write("");
String line = br.readLine();
//Read from the original file and write to the new
//unless content matches data to be removed.
while (line != null) {
String[] tokens = line.split(";");
if (! tokens[0].equals(lineToRemove)){
osw_temp.write(line);
osw_temp.flush();
}
line = br.readLine();
}
osw_temp.close();
br.close();
//Delete the original file
inFile.delete();
//Rename the new file to the filename the original file had.
tempFile.renameTo(inFile);
return true;
}catch (Exception ex) { return false;}
I think there is a problem with using File, is there another way of writing on android internal storage ?
Thanks in advance for your help
EDIT : because using File = new File + rename + deleted methods weren't working here is the solution that I find out. Maybe not the best but at least it works
try {
FileInputStream fIn = openFileInput(path);
InputStreamReader isr = new InputStreamReader(fIn);
BufferedReader br = new BufferedReader(isr);
//Create temp file
FileOutputStream fOut2 = openFileOutput("te.txt", Context.MODE_WORLD_WRITEABLE);
OutputStreamWriter osw2 = new OutputStreamWriter(fOut2);
osw2.write("");
// save and close
osw2.flush();
osw2.close();
// Adding things to temp file
FileOutputStream fOut_temp = openFileOutput("te.txt", Context.MODE_APPEND);
OutputStreamWriter osw_temp = new OutputStreamWriter(fOut_temp);
osw_temp.write("");
String line = br.readLine();
//Read from the original file and write to the new
//unless content matches data to be removed.
while (line != null) {
String[] tokens = line.split(";");
if (! tokens[0].equals(lineToRemove)){
osw_temp.write(line);
osw_temp.write("\r\n");
osw_temp.flush();
}
line = br.readLine();
}
osw_temp.close();
br.close();
//Delete the original file
FileOutputStream fOut = openFileOutput(path, Context.MODE_WORLD_WRITEABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write("");
// save and close
osw.flush();
osw.close();
//Copy temp file to original file
FileInputStream fIn3 = openFileInput("te.txt");
InputStreamReader isr3 = new InputStreamReader(fIn3);
BufferedReader br2 = new BufferedReader(isr3);
String line4 = br2.readLine() ;
FileOutputStream fOut_temp4 = openFileOutput(path, Context.MODE_APPEND);
OutputStreamWriter osw_temp4 = new OutputStreamWriter(fOut_temp4);
while (line4 != null) {
osw_temp4.write(line4);
osw_temp4.write("\r\n");
osw_temp4.flush();
Toast.makeText(getApplicationContext(),"ecrit", Toast.LENGTH_SHORT).show();
line4 = br2.readLine();
}
osw_temp4.close();
br2.close();
return true;
}catch (Exception ex) {
Toast.makeText(getApplicationContext(),ex.getMessage(), Toast.LENGTH_SHORT).show();
return false;}
}
Using this with Java I'm able to remove the line starts with a, just port in Android thats it.
public class LineRemover
{
static String path = "temp.txt";
static String lineToRemove = "a";
public static void main(String[] args)
{
try {
File inFile = new File(path);
FileInputStream fIn = new FileInputStream(path);
InputStreamReader isr = new InputStreamReader(fIn);
BufferedReader br = new BufferedReader(isr);
FileOutputStream fOut_temp = new FileOutputStream("te.txt");
OutputStreamWriter osw_temp = new OutputStreamWriter(fOut_temp);
osw_temp.write("");
String line = br.readLine();
//Read from the original file and write to the new
//unless content matches data to be removed.
while (line != null) {
String[] tokens = line.split(";");
if (! tokens[0].equals(lineToRemove)){
osw_temp.write(line);
osw_temp.flush();
}
line = br.readLine();
}
osw_temp.close();
br.close();
inFile.delete();
inFile = new File("te.txt");
//Rename the new file to the filename the original file had.
inFile.renameTo(new File("temp.txt"));
}catch (Exception ex)
{}
}
}

How do I read .txt assets as UTF-8 in Android through the assetManager?

private void copyMB() {
AssetManager assetManager = this.getResources().getAssets();
String[] files = null;
try {
files = assetManager.list(assetDir);
} catch (Exception e) {
e.printStackTrace();
}
for(int i=0; i<files.length; i++) {
InputStream in = null;
FileOutputStream fos;
try {
in = assetManager.open(assetDir+"/" + files[i]);
fos = openFileOutput(files[i], Context.MODE_PRIVATE);
copyFile(in, fos);
in.close();
in = null;
fos.flush();
fos.close();
fos = null;
} catch(Exception e) {
e.printStackTrace();
}
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
My problem is that UTF-8 character such as åäö is replaced by wierd looking characters. How can I make sure that it my InputStream reader uses UTF-8? In normal Java it would be easy Writing … new InputStreamReader(filePath, "UTF-8"); But since I am getting it from the Asset folder I canot do that (I have to use the assetManager.open() method which wont take "UTF-8" as an argument.
Any ideas? :)
Thank you for your help.
As you write yourself:
new InputStreamReader(in, "UTF-8");
creates a new stream reader with Utf-8 encoding. Just put it in the copyFile() method with your InputStream as the argument.
You can do like this as well:
new InputStreamReader(is, StandardCharsets.UTF_8)

Read/write file to internal private storage

I'm porting the application from Symbian/iPhone to Android, part of which is saving some data into file. I used the FileOutputStream to save the file into private folder /data/data/package_name/files:
FileOutputStream fos = iContext.openFileOutput( IDS_LIST_FILE_NAME, Context.MODE_PRIVATE );
fos.write( data.getBytes() );
fos.close();
Now I am looking for a way how to load them. I am using the FileInputStream, but it allows me to read the file byte by byte, which is pretty inefficient:
int ch;
StringBuffer fileContent = new StringBuffer("");
FileInputStream fis = iContext.openFileInput( IDS_LIST_FILE_NAME );
while( (ch = fis.read()) != -1)
fileContent.append((char)ch);
String data = new String(fileContent);
So my question is how to read the file using better way?
Using FileInputStream.read(byte[]) you can read much more efficiently.
In general you don't want to be reading arbitrary-sized files into memory.
Most parsers will take an InputStream. Perhaps you could let us know how you're using the file and we could suggest a better fit.
Here is how you use the byte buffer version of read():
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) != -1) {
fileContent.append(new String(buffer));
}
This isn't really Android-specific but more Java oriented.
If you prefer line-oriented reading instead, you could wrap the FileInputStream in an InputStreamReader which you can then pass to a BufferedReader. The BufferedReader instance has a readLine() method you can use to read line by line.
InputStreamReader in = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(in);
String data = br.readLine()
Alternatively, if you use the Google Guava library you can use the convenience function in ByteStreams:
String data = new String(ByteStreams.toByteArray(fis));
//to write
String data = "Hello World";
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput(FILENAME,
Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
//to read
String ret = "";
try {
InputStream inputStream = openFileInput(FILENAME);
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e(TAG, "File not found: " + e.toString());
} catch (IOException e) {
Log.e(TAG, "Can not read file: " + e.toString());
}
return ret;
}
context.getFilesDir() returns File object of the directory where context.openFileOutput() did the file writing.

Categories

Resources