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.
Related
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
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 check if a file exists in Java?
(19 answers)
Closed 7 years ago.
I'm creating a file with writeToFile() function.
Before I call writeToFile() function, I want to check if the file already exist or not.
How can I do this?
code:
private void writeToFile(String data, String fileName) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(this.openFileOutput(fileName, Context.MODE_APPEND));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
You could utilize java.io.File and call the .exists() method to check if the file exists.
Use the following code to check if a file already exists.
if(file.exists() && !file.isDirectory()) {
// continue code
}
Using java.io.File
File f = new File(fileName);
if (f.exists()) {
// do something
}
This is a duplicate.
File file = new File("FileName");
if(file.exists()){
System.out.println("file is already there");
}else{
System.out.println("Not find file ");
}
The methods in the Path class are syntactic, meaning that they operate on the Path instance. But eventually you must access the file system to verify that a particular Path exists
This question already has answers here:
How to append text to an existing file in Java?
(31 answers)
Closed 9 years ago.
Everytime I re-ask the user to enter their grades, I have it write a string to the file gradeReport, but everytime the while loop repeats, the previous result is erased. HOw do I get several lines outputted in the file?
//Open file and call writeToFile method
PrintWriter outputFile= new PrintWriter("gradeReport.txt");
outputFile.println(s.writeToFile());
outputFile.close();
And the method:
public String writeToFile()
{
DecimalFormat f = new DecimalFormat("0.00");
String str= name + "--" + id + "--" + f.format(getPercentage())+ "--" + getGrade();
return str;
}
Wrap the PrintWriter around a FileWriter that is set to append to the file.
PrintWriter outputFile= new PrintWriter(new FileWriter("gradeReport.txt", true));
Note 1: the FileWriter constructor's second parameter of true means that it is set to append to the file rather than to over-write the file.
Note 2: this question will likely and appropriately be closed soon as a duplicate.
Try using the constructor
FileWriter(String filename, boolean append)
to open the file in append mode.
FileWriter fw = new FileWriter("filename.txt", true);
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.