append string into File

M

Marcelo

Hi,

I am having a big trouble while saving information into a file. I would
like append some information into file. However, each time that I try to
do this, the information of the file is replaced by the new information.

What is wrong with my routine?


File simFile = new File("simulations.txt");
//System.out.println("simulations: "+simFile.getAbsolutePath());
try{
if(simFile == null)
throw new IOException();

BufferedWriter output = new BufferedWriter(new FileWriter(simFile));

String text = simObj.getInfo();
output.append(text);
//output.newLine();
closeFile(output);
}catch(IOException e){
System.err.println("Cannot save Simulation into file");
}

thanks very much,


Marcelo
 
R

Roedy Green

I am having a big trouble while saving information into a file. I would
like append some information into file. However, each time that I try to
do this, the information of the file is replaced by the new information.

See http://mindprod.com/applets/fileio.html

Ask it to generate you some code to handle your problem.

The code you wrote is SUPPOSED to overwrite.
 
Joined
May 8, 2008
Messages
1
Reaction score
0
this should help, it appends code to the file

/*
* Created on May 2, 2008
*
* This is the function used for WRTIE_TO_FILE procedure this takes
* only text and write into the format
* Author:: Anudeep Kansal
*/
package cToJava;

import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;

/**
* @
*
* TODO To change the template for this generated type comment go to Window -
* Preferences - Java - Code Style - Code Templates
*/
public class WriteToFile{

private static int nextSerialNum = 0;
private static ThreadLocal serialNum = new ThreadLocal() {
protected synchronized Object initialValue() {
nextSerialNum++; return new Integer(nextSerialNum);
}
};
public static ThreadLocal getSerialNum() { return serialNum; }

static File file = new File("WRITE_TO_FILE"
+ getSerialNum() + ".txt");
static boolean append = true;

public static void Write_To_File(int var, String str, String str1) {
try {
FileWriter fw = new FileWriter(file,append);
//br=new BufferedWriter(new FileWriter(file));
if (file.exists()) {
fw.append("Debug String:: " + var + " , " + str + " , " + str1
+ ".\n");
fw.flush();
} else {
file.createNewFile();
fw.append("Debug String:: " + var + " , " + str + " , " + str1
+ ".\n");
fw.flush();
}
}
catch (Exception ex) {
System.out.println("Exception Occured:: ");
ex.printStackTrace();
}
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,020
Latest member
GenesisGai

Latest Threads

Top