Just change PrintWriter out = new PrintWriter(log); to

PrintWriter out = new PrintWriter(new FileWriter(log, true));
Answer from Qiang Jin on Stack Overflow
๐ŸŒ
Reddit
reddit.com โ€บ r/javahelp โ€บ how to write to a file without overwriting?
r/javahelp on Reddit: How to write to a file without overwriting?
January 10, 2018 -

So 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.

๐ŸŒ
RoseIndia
roseindia.net โ€บ java โ€บ javafile โ€บ How-to-Write-to-a-File-in-Java-without-overwriting.shtml
How to Write to a File in Java without overwriting
This tutorial teaches you how to write to a file in Java without overwriting the existing content. This type of application is useful in writing the application log data into a file. In this this we have a "log.txt" file which already contains the data and our program will write to this file without overwriting the content of "log.txt" file.
๐ŸŒ
Coderanch
coderanch.com โ€บ t โ€บ 408804 โ€บ java โ€บ Write-somethin-overwriting
Write somethin' out without overwriting (Beginning Java forum at Coderanch)
November 25, 2007 - Because even your solution that ... 6 code of the constructor you're using: In other words: the File is wrapped in a FileOutputStream, that is wrapped in an OutputStreamWriter, that is wrapped in a BufferedWriter....
๐ŸŒ
Reddit
reddit.com โ€บ r/learnprogramming โ€บ [java] write to existing file without overwriting said text file
r/learnprogramming on Reddit: [Java] Write to existing file without overwriting said text file
February 20, 2017 -

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();

	}
}
๐ŸŒ
Chief Delphi
chiefdelphi.com โ€บ technical โ€บ java
File IO without overwriting file - Java - Chief Delphi
January 19, 2014 - PrintStream writer; DataOutputStream myFile; FileConnection con; try { con = (FileConnection)Connector.open("file:///test.txt", Connector.WRITE); con.create(); myFile = con.openDataOutputStream(); writer = new PrintStream(myFile); } catch (E...
๐ŸŒ
Sololearn
sololearn.com โ€บ en โ€บ Discuss โ€บ 712350 โ€บ how-can-i-write-in-a-file-that-already-exists-without-overwriting-it
How can I write in a file that already exists without overwriting it? | Sololearn: Learn to code for FREE!
For example, if I have a file with one line written, how can I start from the second line? ... open > append > close. https://stackoverflow.com/questions/1625234/how-to-append-text-to-an-existing-file-in-java
Find elsewhere
๐ŸŒ
YouTube
youtube.com โ€บ dr c
CS162 Java = File Output Without Overwriting = Part 6 - YouTube
Computer Science 162 at Tillamook Bay Community College
Published ย  May 6, 2022
Views ย  563
๐ŸŒ
javaspring
javaspring.net โ€บ blog โ€บ inserting-text-into-an-existing-file-via-java
How to Insert Text into an Existing File in Java Without Overwriting Content: A Step-by-Step Guide โ€” javaspring.net
Insert the new text at the desired line index. Write the modified list back to the file. import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCharsets; import java.util.List; public class InsertAtLineNumber { public ...
Top answer
1 of 2
3

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.

2 of 2
0

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.

Top answer
1 of 3
11

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) {
}
2 of 3
4

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();
๐ŸŒ
Coderanch
coderanch.com โ€บ t โ€บ 451009 โ€บ java โ€บ writing-textfile-overwriting-contents
writing to textfile without overwriting contents (I/O and Streams forum at Coderanch)
July 23, 2009 - Still there must be more elegant ... out your suggestion using the old version of the method, sujay. ... Try using a StringBuilder (or StringBuffer in Java 1.4) instead of this form of string concatenation....
๐ŸŒ
Coderanch
coderanch.com โ€บ t โ€บ 518979 โ€บ java โ€บ write-text-files-overwriting-original
how to write to text files without overwriting the original contents (I/O and Streams forum at Coderanch)
December 1, 2010 - private class ButtonHandler implements ActionListener,Serializable { public void actionPerformed(ActionEvent e) { Form1 form1 = new Form1(); String x = ""; File file = new File("client.txt"); /** try { RandomAccessFile Rfile = new RandomAccessFile("client.txt","rw"); long n = 10; Rfile.seek(n); } catch(FileNotFoundException j){}catch(IOException nb){} */ try { FormLogic logic = new FormLogic(); PrintWriter out = new PrintWriter(new FileWriter(file)); logic.setName(nameText.getText()); String schooldata = (String) boxForSchoolsComboBox.getSelectedItem(); String graduatedata = (String)graduateDe
๐ŸŒ
Sololearn
sololearn.com โ€บ en โ€บ Discuss โ€บ 354078 โ€บ how-can-i-write-data-to-a-file-without-overwriting-the-current-content-in-the-file-
How can i write data to a file without overwriting the current ...
Sololearn is the world's largest community of people learning to code. With over 25 programming courses, choose from thousands of topics to learn how to code, brush up your programming knowledge, upskill your technical ability, or stay informed about the latest trends.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 28146336 โ€บ how-to-write-multiple-text-in-file-without-overwriting-it
java - How to write multiple text in file without overwriting it - Stack Overflow
... // create an output stream to the file in append mode rather than overwrite mode FileOutputStream out = new FileOutputStream("BankAccounts.txt", true); // create a Formatter which writes to this stream Formatter formatter = new Formatter(out);
๐ŸŒ
Sentry
sentry.io โ€บ sentry answers โ€บ java โ€บ how to create a file and write to it in java
How to create a file and write to it in Java | Sentry
This enables append mode, so the file will not be overwritten. import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; public class Main { public static void main(String[]args) { String stringToWrite = "\nJava files are easy"; try { BufferedWriter writer = new BufferedWriter(new FileWriter("newfile.txt", true)); writer.write(stringToWrite); writer.close(); } catch (IOException ioe) { System.out.println("Couldn't write to file"); } } }
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 14916582 โ€บ java-how-to-write-to-text-files-without-overwriting-and-writing-on-new-lines
Java: How to write to text files without overwriting and writing on new lines - Stack Overflow
April 29, 2017 - If that is your concern, then the simple fix is to start by appending an empty line; e.g. filewriter.write(newline); where newline contains the appropriate line termination character or characters.