This question already has answers here:
How to write data with FileOutputStream without losing old data?
(2 answers)
Closed 8 years ago.
In the below code I am trying to append some text to a file using FileOutputStream and BufferedWriter as shown below.At ru time, despite the file has some data, when i use FileOutputStream and BufferedWriter i found the file is empty and even the data i want to append bw.write("new information"); is not existing the file is completely empty.
Kindly please let me know how to fix it.
Code:
File f = new File(SystemConfig.getSystConfigInstance("E"));
System.out.println(f.getAbsolutePath() + " name: " + f.getName());
OutputStream os = new FileOutputStream(f);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
bw.write("new information");
Try this, FileOutputStream(File file,
boolean append) with append
OutputStream os = new FileOutputStream(f, true);
If the append boolean is true which means it will append the new content with the old content.
instead of
OutputStream os = new FileOutputStream(f);
FileOutputStream has the default append method also. So use this to append the content with the old one.
File f = new File(SystemConfig.getSystConfigInstance("E"));;
System.out.println(f.getAbsolutePath() + " name: " + f.getName());
OutputStream os = new FileOutputStream(f,true);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
bw.write("new information");
bw.close();
You have missed append flag for FileOutputStream. Then only it created as appendable. Otherwise it will like a read only.
Next , end of the file you need to close the writer. So that only it will flush entire data.
Try this (please note the boolean passed to FileOutputStream):
File f = new File(SystemConfig.getSystConfigInstance("E"));
System.out.println(f.getAbsolutePath() + " name: " + f.getName());
OutputStream os = new FileOutputStream(f, true); // <--- append = true
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
bw.write("new information");
For more info read the official doc of FileOutputStream:
FileOutputStream(File file, boolean append)
If the second argument is true, then bytes will be written to the end
of the file rather than the beginning.
Related
This question already has answers here:
How to append text to an existing file in Java?
(31 answers)
Closed 6 years ago.
How can I write a new row of data to a .CSV file that already has data in it. So far my code just clears the file and doesn't actually write anything?
BufferedReader br = null;
BufferedWriter bw = null;
String fileString = "patients.csv";
String fileLine = "";
File file = new File(fileString);
br = new BufferedReader(new FileReader(file));
FileWriter fw = new FileWriter(fileString);
bw = new BufferedWriter(fw);
while((fileLine = br.readLine()) != null){
bw.write(fileLine);
}
br.close();
bw.close();
specify true in the constructor java FileWriter to know that the true and append be added to the end of the file if you place it does not overwrite information
FileWriter fw = new FileWriter(fileString,true);
If you want to append to a file using FileWriter then use this Constructor
As per Javadocs
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.
But, back to your code, you will only need to write new data to the FileWriter and not rewrite existing data.
This question already has answers here:
How do I create a file and write to it?
(35 answers)
Closed 8 years ago.
On the output part of my IDE (where all the system.out.println textx appear), I have several lines of text. I want to get them and save them to a text file. What would be the possible code for this?
use System#setOut() to redirect output to FileOutputStream to redirect System output to file
// for restore purpose
PrintStream oldOutStream = System.out;
PrintStream outFile = new PrintStream(
new FileOutputStream("/path/to/file.txt", true));
System.setOut(outFile);
System.out.println("this will goto file");
I assume you know about logging framework and you are not trying to use this for logging something
Yo can replce all sop with fileoutput strem and write everything in file
if you want to write log then you can use log4j
String content = "This is the content to write into file";
File file = new File("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();
I'm using the following code to output a Velocity template to a file :
FileWriter fileWriterOut = new FileWriter(outFile);
logger.debug("encoding " + fileWriterOut.getEncoding());
fileWriterOut.write(template.getStringWriter().toString());
fileWriterOut.close();
Problem is :
Deployed in a non UTF-8 App Server, outFile is written using default encoding (iso-xxxx).
You can verify it with fileWriterOut.getEncoding()
It seems that no method in FileWriter class could set another encoding.
How can I force UTF-8 when writing my file ?
Use a FileOutputStream in combination with an OutputStreamWriter:
final OutputStream out = new FileOutputStream(...);
final Writer writer
= new OutputStreamWriter(out, Charset.forName("UTF-8"));
I've found a way to do this, I'm not sure that's the most convenient one, but it works correctly.
Writer out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8"));
out.write(template.getStringWriter().toString());
}
catch ...
finally
{
try {
out.close();
} catch...
}
Assuming I have a txt file located in /mypath/sampletext.txt. How do I append a new line to the beginning of the file with the following in Java while preserving the original text file's contents?:
String startStr ="--Start of File--";
Looking for a way to do this without having to create an intermediary 2nd file and make modifications only to the existing file if possible.
Read file contents first, prepend new line to that like contents = newLine + contents, then write the new conent in the same file (dont append).
well,three ways ,may help you
1.
//true: is append text to fie
FileWriter write = new FileWriter("file_path",true);
writer.write(content);
//open randomFile and "rw"
randomFile = new RandomAccessFile("file_path", "rw");
// file length
long fileLength = randomFile.length();
//point to end index
randomFile.seek(fileLength);
//write
randomFile.writeBytes(content);
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)));
out.write(conent);
New answer is updated...
In this I've use few more FileIO classes & may be their one is deprecated API but If you are aware with Java FileIO classes you can easily fix it.
Here I append new line at the start of file rather than append it to the end of file..
If any issue please comment again....
Try this, I think it will help you..
try
{
//Append new line in existing file.
FileInputStream fr = new FileInputStream("onlineSoultion.txt");
DataInputStream dr = new DataInputStream(fr);
String startStr = "--Start of File--\n";
//String startStr;
while (dr.available() > 0) {
startStr += dr.readLine();
//System.out.println(startStr);
}
dr.close();
fr.close();
FileOutputStream writer = new FileOutputStream("onlineSoultion.txt");
writer.write((new String()).getBytes());
writer.close();
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("onlineSoultion.txt", true)));
out.println(startStr);
out.close();
}
I'm trying to figure out why this doesn't work. All the files which are shown actually exist. The 'logging.toString()' is a .txt file and it reads all the text in the logging and writes it back with the String which I want to be added. Although when I do this, it overwrites it. But I dont want that. Help?
try{
FileWriter fstream = new FileWriter(logging.toString());
BufferedWriter out = new BufferedWriter(fstream);
FileInputStream fstreams = new FileInputStream(logging);
BufferedReader br = new BufferedReader(new InputStreamReader(fstreams));
String strLine;
while ((strLine = br.readLine()) != null){
htmlTextArea = htmlTextArea + strLine + "\n";
}
out.write(htmlTextArea + logto);
out.close();
} catch (Exception ex){}
Why wouldn't it? You don't pass an append flag:
FileWriter(String filename, boolean append)
The API docs are your friend; they're often helpful for understanding behavior.
Change this line
FileWriter fstream = new FileWriter(logging.toString());
to
FileWriter fstream = new FileWriter(logging.toString(), true);
That way, you tell Java you wish to APPEND the file. There's more in the Javadocs for FileWriter.
Because that's the way FileWriter is implemented.
If you want to append, you should use a different constructor: new FileWriter( logging.toString(), true );
If you want to add something to file but not overwrite it use
FileWriter fstream = new FileWriter(logging.toString(),true);