This question already has answers here:
How to append text to an existing file in Java?
(31 answers)
Closed 6 years ago.
I want to know how do I write a line to a file without clearing or flushing it. What classes and packages do I need?
I've tried with FileOutputStream and PrintStream (using println) and with BufferedWriter and OutputStreamWriter (using write) but they erase the previous content from the file.
try
{
File txt = new File("marcos.txt");
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
writer.write(registro);
writer.newLine();
writer.close();
}
catch(Exception e)
{
System.out.println("Error en la escritura al archivo.");
}
You can use the method writeStringToFile under the class FileUtils from org.apache.commons.io
public static void writeStringToFile(File file,
String data,
Charset encoding,
boolean append)
throws IOException
Writes a String to a file creating the file if it does not exist.
Parameters:
file - the file to write
data - the content to write to the file
encoding - the encoding to use, null means platform default
append - if true, then the String will be added to the end of the file rather than overwriting
Throws:
IOException - in case of an I/O error
Related
This question already has answers here:
How to write data with FileOutputStream without losing old data?
(2 answers)
Closed 4 years ago.
I am trying to redirect the console input to a file. Problem is that every time i create a file it overwrites it or creates new files if I select the name of file to include unix timestamp. I saw similar questions here but I am not sure which approach or class to use.
PrintStream out;
PrintStream oldout = new PrintStream(System.out);
try {
out = new PrintStream(
new FileOutputStream(
workFolder + File.separator + "output" + Instant.now().getEpochSecond() + ".txt"));
System.setOut(out);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.setOut(oldout);
So if there isn't a file to create it, but if there is already a file to just append new data, but not overwrite or create new files.
As per Java docs
public FileOutputStream(String name,
boolean append)
throws FileNotFoundException
Parameters: name - the system-dependent file name
append - if true,
then bytes will be written to the end of the file rather than the
beginning
There is a constructor which allows passing the boolean value which decides whether to append the data in file or not.
You can use it.
This question already has answers here:
How do I create a file and write to it?
(35 answers)
Closed 4 years ago.
I am new to File Streams and would appreciate some help. The following code is the code I use to write to a specified file.
OutputStream outStream = new FileOutputStream(file);
outStream.write(contentsToWrite.getBytes());
outStream.close();
How do I save different lines to a file? In my case using \n does not work when writing to a file.
How do I save a line to the file without deleting the other lines?
There is a nice, simple method which allows you to do this with a List of Strings you want to write and the file itself.
List<String> lines=new ArrayList<>(contentToWrite);//if it is an array or something that isn't a list
Files.write(file.toPath(),lines);
Java has some wrapper class to file streams. BufferedWriter can be used to write string to file.
boolean append = true;
String filename = "/path/to/file";
BufferedWriter writer = new BufferedWriter(new FileWriter(filename, append));
// OR: BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename, append)));
writer.write(line1);
writer.newLine();
writer.write(line2);
writer.newLine();
// ......
writer.close();
append meanings you write to the end of the file instead of empty the file.
The FileOutputStream class constructor method has the second parameter. if you set it to true. It will append the content the file you write. And "\r\n" can change to a new line.
OutputStream outStream = new FileOutputStream("a.txt",true);
outStream.write("hello".getBytes());
outStream.write("\r\n".getBytes());
outStream.write("hello".getBytes());
outStream.close();
This question already has answers here:
Is this the best way to rewrite the content of a file in Java?
(8 answers)
Closed 6 years ago.
I have a file that contains only a very small amount of information that needs to be updated periodically. In other words, I want to truncate the file before writing to it. The easiest solution I found was to delete and create it again as shown here:
File myFile = new File("path/to/myFile.txt");
myFile.delete();
myFile.createNewFile();
// write new contents
This 'works' fine, but is there a better way?
There is no need to delete the file and recreate one. If you are writing to the file, for instance using PrintWriter, it will overwrite your current file content.
Example:
public static void main(String[] args) throws IOException
{
PrintWriter prw= new PrintWriter (“MyFile.txt”);
prw.println("These text will replace all your file content");
prw.close();
}
It will only append to the end of the file if you use the overloaded version of the PrintWriter constructor:
PrintWriter prw= new PrintWriter (new FileOutputStream(new File("MyFile.txt"), true));
//true: set append mode to true
In the below example, the "false" causes the file to be overwritten, true would cause the opposite.
File file=new File("C:\Path\to\file.txt");
DataOutputStream outstream= new DataOutputStream(new FileOutputStream(file,false));
String body = "new content";
outstream.write(body.getBytes());
outstream.close();
This question already has answers here:
How do I save a String to a text file using Java?
(24 answers)
Closed 8 years ago.
Ive finished an application and have tested all the functions and they are working. However one part of inputted data is supposed to be saved to a .txt file. Ive placed this inside a string but Im a bit out of my depth in this area and have no idea how to save this to a drive on my PC. Any help is appreciated. The code is on this link: http://sharetext.org/fSy2
Try This:
public static void main(String args[])throws IOException {
File file = new File("Hello1.txt");
// creates the file
file.createNewFile();
// creates a FileWriter Object
FileWriter writer = new FileWriter(file);
// Writes the content to the file
writer.write("This\n is\n an\n example\n");
writer.flush();
writer.close();
}
Read more abut here
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to append text to an existing file in Java
I want to add data to a text file. So it's one after another...so something like:
1
2
3
<add more here>
But I don't want the text from the file to be deleted at all. This is the code i'm using atm, but it replaces what ever is in the file. Could someone please tell me how to do what I asked. Thanks.
FileWriter fstream = new FileWriter("thefile.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write("blabla");
out.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
use this
FileWriter fstream = new FileWriter("thefile.txt",true);
the explanation
public FileWriter(String fileName, boolean append) throws IOException
Constructs a FileWriter object given a file name with a boolean indicating whether or not to append the data written.