append to file android - java

hey there, i need to append to my file but it is not working, it keeps overwriting the file, can anyone please tell me what is wrong:
public void generateNoteOnSD(String sBody){
try
{
File root = new File(Environment.getExternalStorageDirectory(), "AdidasParticipants");
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, "participants.txt");
BufferedWriter bW;
bW = new BufferedWriter(new FileWriter(gpxfile));
bW.write(sBody);
bW.newLine();
bW.flush();
bW.close();
//Toast.makeText(mContext, "Tus datos han sido guardados", Toast.LENGTH_SHORT).show();
}
catch(IOException e)
{
e.printStackTrace();
// importError = e.getMessage();
// iError();
}
}
Thanks in advance.

You can fix it by changing the line where you assign the BufferedWriter:
bW = new BufferedWriter(new FileWriter(gpxfile, 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.

Related

New Line while writing into file

I followed this link and I came up with below code
try {
File file = new File(
"C:/dataset.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
List<Integer> data = generateData(args);
// one per line
for (final int i : data) {
bw.write(i);
bw.newLine(); // Here it throws NullPointerException
}
bw.close();
} catch (IOException e) {
System.out.print(e);
}
NOTE: Even if I move bw.newLine(); before for loop, it throws NullPointerException.
Image
Am I missing anything ?
To add a line seperator you could use this.
//to add a new line after each value added to File
String newLine = System.getProperty("line.separator");
and then call it like so:
bw.write(newLine);
EDIT:
since you cant use a System.getProperty with a BufferWriter I would suggest the code below:
private FileOutputStream fOut;
private OutputStreamWriter writer;
fOut = openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
writer = new OutputStreamWriter(fOut);
writer.append(.... whatever you wish to append ...);
writer.append(separator);
writer.flush();
fOut.close();
Hope that helps!

Editing file in External Storage

In my app, I am writing a file and storing it in external storage
But everytime I want to edit it, I have to get the data of file, delete it and then recreate it using the new data.
But is there any way to directly edit a existing file instead of deleteing and recreating it?
Thanks to blackbelt for helping me out.
Here is how to do this -
File gpxfile = new File(File address, "filename.txt");
BufferedWriter bW;
try {
bW = new BufferedWriter(new FileWriter(gpxfile));
bW.write("file text");
bW.newLine();
bW.flush();
bW.close();
} catch (IOException e) {
e.printStackTrace();
}
This will rewrite the file. If you just want to add a line instead of replacing the whole thing, then replace
bW = new BufferedWriter(new FileWriter(gpxfile));
with
bW = new BufferedWriter(new FileWriter(gpxfile, true));

File fails to save when filename is modified

I have a button that opens a save dialog window with default extension filters set, but when the user does not provide a file name extension on the file name, it should add the extension automatically. The problem is that when this happens the file will not save (or fail to save) but does not throw any exception. The file save successfully pop-up shows up telling the user that the file has been saved successfully but no file was found in the directory. Here's my code:
private void saveRecordsButtonActionPerformed(java.awt.event.ActionEvent evt)
{
if(evt.getSource() == this.saveRecordsButton)
{
String recordName = JOptionPane.showInputDialog(this, "Please type in the name of the record you are about to export: ", "Input Notice", JOptionPane.INFORMATION_MESSAGE);
if(recordName == null || recordName.equals(""))
{
JOptionPane.showMessageDialog(this, "You must type in the name of the record in order to save!", "Input Error!", JOptionPane.ERROR_MESSAGE);
return;
}
int returnVal = this.fileChooser.showSaveDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION)
{
//ObjectOutput oos = null;
try
{
File file = this.fileChooser.getSelectedFile();
String recordDate = this.viewByDateCB.getSelectedItem().toString();
XMLTableProducer xmlTableProducer = new XMLTableProducer(this.cbtm, "Cash Book Table", recordName, recordDate, new Date());
if(!file.getName().contains("."))
{
FileNameExtensionFilter filter = (FileNameExtensionFilter)this.fileChooser.getFileFilter();
file = new File(file.getName()+(filter.getExtensions())[0]);
System.out.println(file.getName()); //This actually prints out the exact file name with extension the way I want
}
// if file doesnt exists, then create it
if(!file.exists())
{
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw);
out.print(xmlTableProducer.getDynamicText());
out.close();
bw.close();
JOptionPane.showMessageDialog(this, "File Saved Successfully!", "Saved", JOptionPane.INFORMATION_MESSAGE);
}
catch(IOException xcp)
{
xcp.printStackTrace(System.err);
}
}
}
}
This file = new File(file.getName()+(filter.getExtensions())[0]); is stripping the path of the File...
Let's say that the user choose to save the file in C:\My Documents\Boss. When you as File#getName it will only return Boss. Which now means that the file will be saved to the same location that the program is being executed from (ie .\Bosss)
Instead file = new File(file.getName()+(filter.getExtensions())[0]);, you should be using file = new File(file.getPath()+(filter.getExtensions())[0]); which return the "full" path and file name represented by the File
Updated...
Your file writing process is also a little off.
A general rule of thumb, if you open the stream, you should close it...
You shouldn't be closing the resources within the try-catch, if an Exception occurs within the try-catch, the close methods will never be called, leaving the resources open...
try
{
/*...*/
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw);
out.print(xmlTableProducer.getDynamicText());
out.close();
bw.close();
JOptionPane.showMessageDialog(this, "File Saved Successfully!", "Saved", JOptionPane.INFORMATION_MESSAGE);
}
catch(IOException xcp)
{
// If an exception occurs, the file will remain open
xcp.printStackTrace(System.err);
}
Instead, you should use the finally block to try and close all your resources, for example...
BufferedWriter bw = null;
try
{
/*...*/
FileWriter fw = new FileWriter(file.getAbsoluteFile());
bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw);
out.print(xmlTableProducer.getDynamicText());
JOptionPane.showMessageDialog(this, "File Saved Successfully!", "Saved", JOptionPane.INFORMATION_MESSAGE);
}
catch(IOException xcp)
{
xcp.printStackTrace(System.err);
} finally {
try
{
bw.close();
}
catch (Exception exp) {
}
}
The code looks okay. Since you see no exception, I suspect you are not looking at the correct directory. After
// if file doesn't exists, then create it
if(!file.exists())
{
file.createNewFile();
}
add
System.out.println(file.getAbsolutePath());
Verify that the directory you are looking in to is the path shown there..

How to free the content of a file?

I want to write in a file, if it exists i would like to free the content and to write from the begining of the file this the code that i use but i dont now how to do that.
try {
File f = new File(testPath + "/logtest.txt");
if (f.exists()) {
f.delete();
BufferedWriter bw = new BufferedWriter(new FileWriter(f, true));
bw.write(text);
bw.newLine();
bw.close();
} else {
BufferedWriter bw = new BufferedWriter(new FileWriter(f, true));
bw.write(text);
bw.newLine();
bw.close();
}
} catch (Exception e) {
}
You have to use
BufferedWriter bw = new BufferedWriter(new FileWriter(f, false));
the second parameter append in the FileWriter constructor you are using is a flag witch controls whether the file sould be truncated before the first write or the data writen should be appended.
see javadoc
The second argument to the FileWriter constructor allows to specify whether you want to append to or overwrite the content:
public FileWriter(File file, boolean append) throws IOException
Constructs a FileWriter object given a File object. If the second
argument is true, then bytes will be written to the end of the file
rather than the beginning.
Parameters:
file - a File object to write to
append - if true, then
bytes will be written to the end of the file rather than the beginning
In your code, you pass true. Simply change it to false:
BufferedWriter bw = new BufferedWriter(new FileWriter(f, false));
EDIT: in case the code you gave in your question is inside a loop, here's how you should change it:
try {
File f = new File(testPath + "/logtest.txt");
if (f.exists()) {
f.delete();
}
BufferedWriter bw = new BufferedWriter(new FileWriter(f, false));
for/while (...) { // your loop here
// extract your text
bw.write(text);
}
bw.close();
f.close();
} catch (Exception e) {
// handle exceptions...
}
Doing this will overwrite whatever was there earlier.
String fileName = "foo.txt";
FileWriter fw = null;
try{
fw = new FileWriter(fileName);
fw.write("haha");
} catch (IOException e) {
System.err.println("Could not write to the file.");
}finally{
if(fw!=null)
try {
fw.close();
} catch (IOException e) {
System.err.println("Could not close the file.");
}
}
If you want to append the data use
fw.append();
Try below code.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
public class FileClient {
public static void main(String[] args) {
try {
String content = "Hello test";
File file = new File("D:\\filename.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
System.out.println("Done");
} catch (Exception e) {
e.printStackTrace();
}
}
}
You got your file deleted, because you do a f.delete(); in a loop.
You should do a construction like this:
File f = new File(testPath + "/logtest.txt");
if (f.exists()) {
f.delete();
}
BufferedWriter bw = new BufferedWriter(new FileWriter(f, false));
while (...)
String text = ...;
bw.write(text);
bw.newLine();
}
bw.close();
This way you create/delete the file only once.

Saving String Input on Android

Right, I've been trying to find a solution to this for a good while, but it's just not working for some reason.
In short, what I want to do is save every input String the user inputs into a file. Every time the activity is created again, I want to re-input these strings into a new instance of an object.
This code is what I use to create the file and read info from it, used in the onCreate() method of activity
try {
String brain = "brain";
File file = new File(this.getFilesDir(), brain);
if (!file.exists()) {
file.createNewFile();
}
BufferedReader in = new BufferedReader(new FileReader(file));
String s; // This feeds the object MegaAndroid with the strings, sequentially
while ((s = in.readLine()) != null) {
MegaAndroid.add(s);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
After that, every time the user inputs some text, the strings are saved onto the file:
try {
String brain = "brain";
File file = new File(this.getFilesDir(), brain);
if (!file.exists()) {
file.createNewFile();
}
BufferedWriter out = new BufferedWriter(new FileWriter(file));
out.write(message); // message is a string that holds the user input
out.close();
} catch (IOException e) {
e.printStackTrace();
}
For some reason, however, every time the application is killed, the data is lost.
What am I doing wrong?
EDIT: Also, if I were to access this file from another class, how can I?
As we discussed in the commend section the chief problem with the code is that your execution of FileWriter occurred prior to your FileReader operation while truncating the file. For you to maintain the file contents you want to set the write operation to an append:
BufferedWriter out = new BufferedWriter(new FileWriter(file,true));
out.write(message);
out.newLine();
out.close();
However, if every entry on the EditText is received then shipped into the file you'll just be writing data byte after byte beside it. It is easy to get contents similar to
This is line #1This is line #2
Instead of the desired
This is line #1
This is line #2
which would be corrected by having the BufferedWriter pass a newline after each write to the file.
This is what I do for file reading.
try{
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/whereyouwantfile");
dir.mkdirs();
Log.d(TAG,"path: "+dir.getAbsolutePath());
File file = new File(dir, "VERSION_FILENAME");
FileInputStream f = new FileInputStream(file);
//FileInputStream fis = context.openFileInput(VERSION_FILENAME);
BufferedReader reader = new BufferedReader(new InputStreamReader(f));
String line = reader.readLine();
Log.d(TAG,"first line versions: "+line);
while(line != null){
Log.d(TAG,"line: "+line);
//Process line how you need
line = reader.readLine();
}
reader.close();
f.close();
}
catch(Exception e){
Log.e(TAG,"Error retrieving cached data.");
}
And the following for writing
try{
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/whereyouwantfile");
dir.mkdirs();
File file = new File(dir, "CONTENT_FILENAME");
FileOutputStream f = new FileOutputStream(file);
//FileOutputStream fos = context.openFileOutput(CONTENT_FILENAME, Context.MODE_PRIVATE);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(f));
Set<String> keys = Content.keySet();
for(String key : keys){
String data = Content.get(key);
Log.d(TAG,"Writing: "+key+","+data);
writer.write(data);
writer.newLine();
}
writer.close();
f.close();
}
catch(Exception e){
e.printStackTrace();
Log.e(TAG,"Error writing cached data.");
}
You can use the private mode if you don't want the rest of the world to be able to see your files, but it is often useful to see them when debugging.

Categories