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();
Related
I am trying to program a simple todo app for my android phone. Ive gotten far enough that I would like to save these strings that I input. However, every time I try to write the data I get a file not found exception. Here is the code I use in my onCreate method to instantiate the File.
File path = getFilesDir();
File itemFile = new File(path,"Todo_File.txt");
I then have two methods, one to write to the File, and the other to read from it. They look like this:`
public void readItems() {
try {
BufferedReader reader = new BufferedReader(new FileReader("Todo_File.txt"));
while(reader.readLine()!=null){
items.add(reader.readLine());
}
} catch(IOException e) {
e.printStackTrace();
}
}
and
public void writeItems() {
try{
BufferedWriter writer = new BufferedWriter(new FileWriter("Todo_File.txt"));
for(int i=0;i<items.size();i++){
writer.write(items.get(i));
}
} catch (IOException e){
e.printStackTrace();
}
}
items is a stringArray which holds the strings that were input. Every time that I try to write or read the files I get the following exception:
W/System.err: java.io.FileNotFoundException: Todo_File.txt (No such file or directory)
I don't understand why Android Studio cant find the file that I created, can anyone help?
You are looking for a file "Todo_File.txt".
Where have you kept this file?
Are you keeping it as a resource file in the "res/raw" directory of your app or it is lying somewhere in the phone storage?
Here you can get some idea of types of the storage
https://developer.android.com/guide/topics/data/data-storage.html
https://android.stackexchange.com/questions/112951/two-types-of-internal-storage-what-is-the-difference
Mostly likely I guess you need to correct the path of this file.
here are the way to get the "/storage/sdcard0/" path
Environment.getExternalStorageDirectory()
The standard way to do File-IO in Android is using the context-relevant IO-methods.
To write a file, use the following code. Details about the different file-modes are available here.
FileOutputStream fOut = openFileOutput("Todo_File.txt", MODE_WORLD_READABLE);
To read a file, use this:
FileInputStream fIn = openFileInput("Todo_File.txt");
Since you defined
File path = getFilesDir();
File itemFile = new File(path,"Todo_File.txt");
you can do:
public void readItems() {
try {
BufferedReader reader = new BufferedReader(new FileReader(itemFile));
while(reader.readLine()!=null){
items.add(reader.readLine());
}
} catch(IOException e) {
e.printStackTrace();
}
}
public void writeItems() {
try{
BufferedWriter writer = new BufferedWriter(new FileWriter(itemFile));
for(int i=0;i<items.size();i++){
writer.write(items.get(i));
}
} catch (IOException e){
e.printStackTrace();
}
}
You need to actually create the file before you write to it. You should do something like this:
File path = getFilesDir();
File itemFile = new File(path,"Todo_File.txt");
if (!path.exists()) {
path.mkdirs();
}
What you have done is simply tried to read from the file. The fact that you get the error:
W/System.err: java.io.FileNotFoundException: Todo_File.txt (No such file or directory)
Is an indication that the file you want to write to hasn't been created, and I don't see you creating the file anywhere.
If you are using an emulator, you need to make sure that you have an SDK card set up on your device, and then do:
File itemFile = new File(Environment.getExternalStorageDirectory(),"Todo_File.txt");
if (!path.exists()) {
path.mkdirs();
}
I have been been loitering on this site for weeks and have found it invaluable, however I am now stuck and need some pointers please. I am writing an app to create a .txt file on the sd card and then append csv data to it. Here is my code so far:
private void LogData() {
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard, "/DataLogger/my_file.txt");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
if (file.exists()) try {
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write("Example");
writer.write("\n");
writer.write("Text");
writer.write("\n");
writer.flush();
writer.close();
} catch (IOException e1) {
}
}
}
}
From the above, I anticipated that on calling "LogData()" for the first time an empty .txt file would be created and then subsequent runs would populate it. Instead nothing happens at all (no file is created). Prior to the above I have tried every piece of example code on creating a .txt file and nothing work. I am absolutely lost - please help!
And yes, I have added the following to the manifest :-)
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
For information, I am running lollipop 5.0.2 on a Moto G and I am very new to coding.
Thanks in advance.
Use the following code :
try {
file.createNewFile();
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write("Example");
writer.write("\n");
writer.write("Text");
writer.write("\n");
writer.flush();
writer.close();
} catch (IOException e)
{
...
}
Thanks everyone, I was not using the constructor correctly. Correct code:
BufferedWriter writer = new BufferedWriter(new FileWriter(file, true));
When you open a file using the FileWriter constructor that only takes in a File, it will overwrite what was previously in the file. Supplying the second parameter as true tells the FileWriter that you want to append to the end of it. Thanks to #nicholas.hauschild for his answer 4 years ago...
String filename = "myfile";
String string = "Hello world!";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
Ok so the above code creates a file in the internal storage and writes something into it. My question is, where can I find and open this file in Eclipse? I want to see its contents and edit it manually. Or I may want to include my own file and read its contents.
My question is, where can I find and open this file in Eclipse?
Using the file manager in the DDMS perspective, for the default user account on an emulator, go to /data/data/your.application.id.goes.here/files, substituting in the package from your manifest where I have your.application.id.goes.here.
In my application I have a listView. I want to update its content on a regular basis.
I use string XML file in res folder, which contains strings that populate the listView. What I want to do is check for an update when the application starts (assume I have my own updating system on private server), if update is found:
Download new XML file with the new strings, update them in the listView.
From what I read you can't just simply replace the XML files in the res folder.
How can I update the listView content from external XML? Or is there a better way to do it other than this?
Why do I want this? Since I am only updating small content, I don't want the user to download the whole APK file instead of few lines of text.
You can put your xml file in internal storage of application, and whenever you get update just replace your xml file.
Inside your activity,
Use the following functions to update a file.
public synchronized void writeXML(String data) throws IOException {
FileOutputStream fOut = null;
OutputStreamWriter osw = null;
fOut = openFileOutput("yourData.txt", Context.MODE_PRIVATE);
osw = new OutputStreamWriter(fOut);
app.setXMLSize(data.length());
osw.write(data);
osw.close();
fOut.close();
}
private synchronized String readXML() throws IOException {
FileInputStream stream = openFileInput("yourData.txt");
try {
FileChannel fc = stream.getChannel();
MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc
.size());
return Charset.defaultCharset().decode(bb).toString();
} finally {
stream.close();
}
}
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