Managing text files Android - android

I've got a little problem while managing .txt files on Android. I've found this link (it's in Spanish) that explains how to use text files on my Android device.
What I want to do, is create a text file using the intern memory of the device, as I don't want the user depend on a SD card, and a raw text file won't allow me to write on in, only read. So I want a text file that can append some information and, in a particular case, delete all the content in the text file and reset it.
I've written this code for the writing side:
OutputStreamWriter fout = null;
try
{
fout = new OutputStreamWriter(openFileOutput("measures.txt", Context.MODE_APPEND));
fout.write(measure);
}
catch (Exception ex)
{
Log.e("Files", "Error while opening to write file measures.txt");
}
finally
{
try
{
fout.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I guess this part opens the file "measure.txt" in the APPEND mode, or creates it in APPEND mode.
When I try to read from it:
BufferedReader fin = null;
try
{
fin = new BufferedReader(new InputStreamReader(context.openFileInput("medidas.txt")));
String line = fin.readLine();
// Some staff with this line
fin.close()
}
// catch staff
What I want to do is delete all the content in the text file before I close the file. The idea is store the information in another type of variable, and then, when I finish reading from file, reset the content.
How can I do that?

Ok, I solved my problem doing this:
deleteFile("measures.txt");
And that will [i]erase[/i] for sure the file... :P

Related

Deleting all the contents from a text file Android

Here is the code for writing a string to a text file.
try {
OutputStreamWriter out=new OutputStreamWriter(openFileOutput("counts.txt", MODE_APPEND));
try {
s = main_text.getText().toString();
out.write(s);
}
catch (java.io.IOException e) {
}
Now how to delete all the contents of a text file without deleting the file itself.
Actually when ever adding the next string to a file it appends next to the previous string. What is required is to over write the previous string.
you need to use another mode - when you use MODE_APPEND it will append ;-)
I think you should be fine with just changing MODE_APPEND -> 0
open file and try to write blank string into file.
PrintWriter writer = new PrintWriter(file);
writer.print("");
writer.close();

How to save a textview's result into txt or pdf file on the internal storage of the device?

I'm new on android development and i plan to print my result of my calculation on my app through print API, and i will use txt or pdf file for this mission.
for every calculation there is an output which will be as a textview like that:
Result.setText(" Weight + i1+ \nHeight+i2");
the result may be reach 20 lines !!!
and first of all i need to save it as a txt or pdf file on the internal storage of the device ?!
So, if there is any way to do that please help.
I'm assuming that you have some other method for creating a String or byte[] containing your data. When you place them into internal storage, they're saved as raw bytes usually, and the extension name really doesn't mean much (but you can add one if you want).
//create an output stream
FileOutputStream out = null;
try {
//open output to internal storage. filename here is whatever
//you want to use to call it (extensions are optional)
// context can be application or activity context
out = context.openFileOutput(filename, Context.MODE_PRIVATE);
//data is your string or byte block or whatever
out.write(data);
//catch all exceptions
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

Writing to an existing resource XML file in Android

I am trying to write to an existing XML file in the /res/xml directory on an Android device. Two questions:
1) Are these files able to be overwritten?
2) If so, how can I obtain a handle to that file?
I am trying this to no avail:
FileOutputStream fos;
try {
fos = openFileOutput("/res/xml/scores.xml", Context.MODE_PRIVATE);
fos.write(writer.toString().getBytes());
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
UPDATE
Trying to read from the file using:
....
PriorityQueue<Score> scores = new PriorityQueue<Score>();
XmlPullParserFactory xmlFac = XmlPullParserFactory.newInstance();
XmlPullParser qXML = xmlFac.newPullParser();
File scoresFile = new File(c.getExternalFilesDir(null), "scores.xml");
InputStream is = new FileInputStream(scoresFile);
qXML.setInput(is,null);
....
Trying to write to the file using:
....
File scoresFile = new File(getExternalFilesDir(null), "scores.xml");
OutputStream os = new FileOutputStream(scoresFile);
os.write(writer.toString().getBytes());
os.flush();
os.close();
....
You need to use the external storage on the device. You can't and shouldn't be writing to the resources. Instead, copy the resource to the external storage, and then modify it there.
EDIT: You can also use your application's internal data folder to save files to, but again, you will want to copy your resource there if you want to modify it. This will allow the files to remain internal to your application.

Reading int value from txt file on SD card android

So in this app I made, The user makes a project and when they save, the number of frames is saved to numberFrames.txt on the SD card. Then I retrieve the file in another class. Only thing is that nFrames = 50 when i show a toast of nFrames to the screen after I run this code. The only initializing of nFrames I do is to zero right above this code, which is located in the onCreate().
File sdcardLocal = Environment.getExternalStorageDirectory();
File dir = new File (sdcardLocal.getAbsolutePath() + "/Flipbook/"+customizeDialog.getTitle()+"/");
dir.mkdirs();
File fileNum = new File(dir, "numberFrames.txt");
FileWriter myFileWriter = null;
try {
myFileWriter = new FileWriter(fileNum);
} catch (IOException e) {
e.printStackTrace();
}
BufferedWriter out = new BufferedWriter(myFileWriter);
try {
String text = bitmaps.size()+"";
out.write(text);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
I retrieve the file like this. I have no idea where this "50" value for nFrames came from as there are no loops around this and I know for sure that the particular project saved has only 3 frames. Why is this?
FileInputStream is = null;
BufferedInputStream bis = null;
try {
is = new FileInputStream(new File(mFolderDialog.getPath()+"/numberFrames.txt"));
bis = new BufferedInputStream(is);
nFrames = bis.read();
}catch (IOException e) {
e.printStackTrace();
}
You are writing out a string, and then reading the first byte as an integer. 50 is the ascii code for the '2' character.
You can use BufferedReader.readLine to read the entire first line of the file as a String, and then Integer.parseInt to convert that to an integer.
Also, I would take a closer look at your application's workflow. You don't give much information, but saving a file with a single integer value to the sdcard has a certain "smell" to it :). Have you looked at using a database, or maybe store the text file in your application's directory instead?

Is there any way to acces file stored in project folder?

I have several files stored in my project /res/values folder, is there any way to open and read these files from my android application? Each file contains text informations about one level of my game.
I really appreciate any help.
I find what I needed here:
http://developer.android.com/guide/topics/data/data-storage.html
"If you want to save a static file in your application at compile time, save the file in your project res/raw/ directory. You can open it with openRawResource(), passing the R.raw. resource ID. This method returns an InputStream that you can use to read the file (but you cannot write to the original file). "
Sorry if My question was not clear.
And big thanks to Radek Suski for some additional information and example. I appreciate that.
As far I know you can either access files within the directory "files" from your project directory or from the SD-Card.
But no other files
EDIT
FileInputStream in = null;
InputStreamReader reader = null;
try {
char[] inputBuffer = new char[256];
in = openFileInput("myfile.txt");
reader = new InputStreamReader(in);
reader.read(inputBuffer);
String myText = new String(inputBuffer);
} catch (Exception e) {;}
finally {
try {
if (reader != null)reader.close();
} catch (IOException e) {; }
try {
if (in != null)in.close();
} catch (IOException e) {;}
}
Then your file will be located in:
/data/data/yourpackage/files/myfile.txt

Categories

Resources