Just change PrintWriter out = new PrintWriter(log); to
PrintWriter out = new PrintWriter(new FileWriter(log, true));
Answer from Qiang Jin on Stack OverflowSo right now I looked online and found a pretty good solution for writing to a file, but every time I run the program, it overwrites the file instead of adding to it. Here is the code:
try {
//creates a BufferedReader to read the console
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//reads the input line
String lineFromInput = in.readLine();
//creates a file for output
PrintWriter file = new PrintWriter(new FileWriter("C:/Users/sachi/Desktop/log.txt")); //This is the PC location, Mac location is /Users/236969/Desktop/log.txt
//outputs line to file
file.println(lineFromInput);
//closes the file (VERY IMPORTANT!)
file.close();
}
catch(IOException e1) {
System.out.println("Error during reading/writing");
}How do I do this exact same thing but have the program add a new line instead of overwriting every time? I haven't really learned much about BufferedReader and PrintWriter so I don't really know in which direction to look for help.
EDIT: Never mind, I got the solution. For anyone having the same problem, here is the solution.
Just change PrintWriter out = new PrintWriter(log); to
PrintWriter out = new PrintWriter(new FileWriter(log, true));
use a FileWriter instead.
FileWriter(File file, boolean append)
the second argument in the constructor tells the FileWriter to append any given input to the file rather than overwriting it.
here is some code for your example:
File log = new File("log.txt")
try{
if(!log.exists()){
System.out.println("We had to make a new file.");
log.createNewFile();
}
FileWriter fileWriter = new FileWriter(log, true);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write("******* " + timeStamp.toString() +"******* " + "\n");
bufferedWriter.close();
System.out.println("Done");
} catch(IOException e) {
System.out.println("COULD NOT LOG!!");
}
Videos
so this is a part of my project that I'm struggling with. I need to be able to search if a file exists, and if it does then I could append to it without erasing the content of the original file. and if the file does not exist to make a new one. However I'm running into a problem in which when I enter a directory and a file name of a file that doesn't exist, it says it exists, and creates the file and adds data to it regardless of the fact not existing before running the program. What am I doing wrong here. I'm somewhat new to file writing
package writeToFile;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Scanner;
public class writeTo {
public static void main(String[] args) throws Exception{
String fileDirectory;
String fileName;
System.out.println("Please enter the directory to create a new text file (Don't include file name or extension at the end i.e (C:\\Users\\JohnDoe\\Desktop)");
Scanner keyboard = new Scanner(System.in);
fileDirectory = keyboard.nextLine();
System.out.println("Please choose a file name for your text file (Don't Include .txt or any extensions at the end)");
fileName = keyboard.nextLine();
File newFile = new File(fileDirectory + "\\" + fileName +".txt");
FileWriter fileWrite = new FileWriter(newFile, true);
BufferedWriter bufferedWrite = new BufferedWriter(fileWrite);
PrintWriter write = new PrintWriter(bufferedWrite);
if(newFile.exists() == false){
newFile.createNewFile();
write.print("hello new worlkd");
System.out.println("File Created and written to sucessfully, Please check " + fileDirectory +" For the File " + fileName);
}
else{
System.out.println("The File " + fileName +" Already Exists, populating existing file");
write.print("hello old worlkd");
}
write.close();
keyboard.close();
}
}You need use the boolean value true. From docs
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.
Parameters:
fileName - String The system-dependent filename.
append - boolean if true, then data will be written to the end of the file rather than the beginning.
Use second parameter of FileWriter, which is defining if you want to append or not. Just set it to true.
BufferedWriter writer = new BufferedWriter(new FileWriter(
sFileName, true));
Add \n after each line.
First, you are calling createNewFile(). This indicates that you want to create a new file. If you do not want to create a new file, do not call createNewFile(). And, since the documentation for createNewFile() says "This method is not generally useful", you may wish to consider just getting rid of it.
Second, you need to indicate that you want to append to the existing data when you open and use that file. The standard recipe for this:
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("outfilename", true)));
out.println("the text");
out.close();
} catch (IOException e) {
//oh noes!
}
The true in the second parameter to the FileWriter constructor indicates that you want to append instead of overwrite.
Third, do not hardcode paths in Android. /sdcard/Output1.txt has been poor form for years and will not work on some Android devices.
Fourth, do not clutter up the root of external storage. Hence, instead of:
file = new File("/sdcard/Output1.txt");
use:
file = new File(getExtenalFilesDir(null), "Output1.txt");
to put the file in a subdirectory unique for your own app.
Try using java.nio.Files along with java.nio.file.StandardOpenOption
try(BufferedWriter bufWriter =
Files.newBufferedWriter(Paths.get("/sdcard/Output1.txt"),
Charset.forName("UTF8"),
StandardOpenOption.WRITE,
StandardOpenOption.APPEND,
StandardOpenOption.CREATE);
PrintWriter printWriter = new PrintWriter(bufWriter, true);)
{
printWriter.println("Text to be appended.");
}catch(Exception e){
//Oh no!
}
This uses a try-with-resources statement to create a BufferedWriter using Files, which accepts StandardOpenOption parameters, and an auto-flushing PrintWriter from the resultant BufferedWriter. PrintWriter's println() method, can then be called to write to the file.
The StandardOpenOption parameters used in this code: opens the file for writing, only appends to the file, and creates the file if it does not exist.
Paths.get("path here") can be replaced with new File("path here").toPath().
And Charset.forName("charset name") can be modified to accommodate the desired Charset.
It is advised to use chain of BufferedWriter and FileWriter, and the key point is FileWriter will append String to current file when use the one of its constructor that lets appaneding by adding true to last paramter like
new FileWriter("login.txt", true)
and when we surrounding it with BufferedWriter object in order to be more efficient if you are going to write in the file number of time, so it buffers the string in big chunk and write the big chunk into a file and clearly you can save a lot of time for writing into a file
Note :It is possible not to use BuffredWriter ,but it is advised because of better performance and ability to buffer the big chunk of Strings and write them once
Just change your
PrintWriter out = new PrintWriter("login.txt");
to
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("login.txt", true)));
Example:
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("login.txt", true)));) {
String data = "This content will append to the end of the file";
File file = new File("login.txt");
out.println(data);
} catch(IOException e) {
}
It is possible to solve this issue without using BufferedWriter, yet the performance will be low as I mentioned.
Example:
try (PrintWriter out = new PrintWriter(new FileWriter("login.txt", true));) {
String data = "This content will append to the end of the file";
File file = new File("login.txt");
out.println(data);
} catch (IOException e) {
}
Use FileWriter
FileWriter fw = new FileWriter(filename,true);
//the true will append the new data to the existing data
Something like this
PrintWriter out = new PrintWriter(new BufferedWriter(
new FileWriter("login.txt", true)))
out.println(n);
out.println(p);
out.close();