Create a file copy. And supposed the original file is original.

  • write the line Sean to file copy.
  • for each line in file original copy to file copy
  • delete the file original
Answer from Trying on Stack Overflow
Top answer
1 of 6
25

No, there is no way to do that SAFELY in Java. (Or AFAIK, any other programming language.)

No filesystem implementation in any mainstream operating system supports this kind of thing, and you won't find this feature supported in any mainstream programming languages.

Real world file systems are implemented on devices that store data as fixed sized "blocks". It is not possible to implement a file system model where you can insert bytes into the middle of a file without significantly slowing down file I/O, wasting disk space or both.


The solutions that involve an in-place rewrite of the file are inherently unsafe. If your application is killed or the power dies in the middle of the prepend / rewrite process, you are likely to lose data. I would NOT recommend using that approach in practice.

Use a temporary file and renaming. It is safer.

2 of 6
6

There is a way, it involves rewriting the whole file though (but no temporary file). As others mentioned, no file system supports prepending content to a file. Here is some sample code that uses a RandomAccessFile to write and read content while keeping some content buffered in memory:

public static void main(final String args[]) throws Exception {
    File f = File.createTempFile(Main.class.getName(), "tmp");
    f.deleteOnExit();

    System.out.println(f.getPath());

    // put some dummy content into our file
    BufferedWriter w = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f)));
    for (int i = 0; i < 1000; i++) {
        w.write(UUID.randomUUID().toString());
        w.write('\n');
    }
    w.flush();
    w.close();

            // append "some uuids" to our file
    int bufLength = 4096;
    byte[] appendBuf = "some uuids\n".getBytes();
    byte[] writeBuf = appendBuf;
    byte[] readBuf = new byte[bufLength];

    int writeBytes = writeBuf.length;

    RandomAccessFile rw = new RandomAccessFile(f, "rw");
    int read = 0;
    int write = 0;

    while (true) {
                    // seek to read position and read content into read buffer
        rw.seek(read);
        int bytesRead = rw.read(readBuf, 0, readBuf.length);

                    // seek to write position and write content from write buffer
        rw.seek(write);
        rw.write(writeBuf, 0, writeBytes);

                    // no bytes read - end of file reached
        if (bytesRead < 0) {
                            // end of
            break;
        }

                    // update seek positions for write and read
        read += bytesRead;
        write += writeBytes;
        writeBytes = bytesRead;

                    // reuse buffer, create new one to replace (short) append buf
        byte[] nextWrite = writeBuf == appendBuf ? new byte[bufLength] : writeBuf;
        writeBuf = readBuf;
        readBuf = nextWrite;
    };

    rw.close();

            // now show the content of our file
    BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(f)));

    String line;
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }
}
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 16514940 โ€บ how-to-append-a-new-line-to-beginning-of-an-existing-file-in-java
How to append a new line to beginning of an existing file in java? - Stack Overflow
May 24, 2017 - Read file contents first, prepend new line to that like contents = newLine + contents, then write the new conent in the same file (dont append). ... Sign up to request clarification or add additional context in comments.
๐ŸŒ
Coderanch
coderanch.com โ€บ t โ€บ 389927 โ€บ java โ€บ Inserting-line-middle-existing-file
Inserting new line in the middle of a existing file (Beginning Java forum at Coderanch)
When finished reading in the original file, write the temp file back out to it. You could read in input file into an array, and do an insert at the correct place. This could be the beginning of an Editor of some sort if you stuck on a GUI. If the text file is small enough, you could read it into one giant string. Then sub-string the part before the addition, add in your stuff, and concatenate in the last part of the string. "JavaRanch, where the deer and the Certified play" - David O'Meara
๐ŸŒ
Real's HowTo
rgagnon.com โ€บ javadetails โ€บ java-0073.html
Insert a line in a file - Real's Java How-to
[JDK1.1] import java.io.*; public class JInsert { public static void main(String args[]){ try { JInsert j = new JInsert(); j.insertStringInFile (new File(args[0]),Integer.parseInt(args[1]), args[2]); } catch (Exception e) { e.printStackTrace(); } } public void insertStringInFile (File inFile, int lineno, String lineToBeInserted) throws Exception { // temp file File outFile = new File("$$$$$$$$.tmp"); // input FileInputStream fis = new FileInputStream(inFile); BufferedReader in = new BufferedReader (new InputStreamReader(fis)); // output FileOutputStream fos = new FileOutputStream(outFile); PrintWriter out = new PrintWriter(fos); String thisLine = ""; int i =1; while ((thisLine = in.readLine()) != null) { if(i == lineno) out.println(lineToBeInserted); out.println(thisLine); i++; } out.flush(); out.close(); in.close(); inFile.delete(); outFile.renameTo(inFile); } }
๐ŸŒ
Tek-Tips
tek-tips.com โ€บ home โ€บ forums โ€บ software โ€บ programmers โ€บ languages โ€บ java
append to begining of file | Tek-Tips
August 4, 2004 - Heres my RAF code: RandomAccessFile raf = new RandomAccessFile(nm,"rw"); raf.seek(0); raf.writeBytes("USER;ACTION;DIALOG"); // raf.writeBytes("\n"); // inserting this line is not helping anyway... raf.close(); My original file: // <- this is the blank line sands;testing;cude;munde sands;testing;cude;munde My RAF modified file : as u can c some data is missing...
Find elsewhere
๐ŸŒ
The Coding Forums
thecodingforums.com โ€บ archive โ€บ archive โ€บ java
How to append to the start of text file? | Java | Coding Forums
August 24, 2004 - I believe the : FileWriter only allows you to append at the end of the text file, and not at : the start. Well that's the meaning of append, isn't it? To put it at the beginning you need to prepend, not append.
๐ŸŒ
Delft Stack
delftstack.com โ€บ home โ€บ howto โ€บ java โ€บ append to a text file in java
How to Append Text to a Text File in Java | Delft Stack
February 2, 2024 - The \r and \n are used to insert the text at the beginning of a new line. import java.io.FileOutputStream; public class Main { public static void main(String args[]) { try { String filePath = "C:\\Users\\Lenovo\\Desktop\\demo.txt"; FileOutputStream ...
Top answer
1 of 2
1

If you can keep all lines in memory, that helps for writing to the same file:

    Path inputFile = Paths.get("inputfile.txt");
    Charset charset = Charset.getDefault();
    List<String> lines = Files.readAllLines(inputFile, charset);
    try (PrintWriter out = new PrintWriter(
            Files.newBufferedWriter(inputFile, charset,
                StandardOpenOptions.TRUNCATE_EXISTING))) {
        int lineno = 0;
        for (String line : lines) {
            ++lineno;
            out.printf("%d. %s%n", lineno, line);
        }
    }

You can use a fixed Charset like Charset.UTF_8, and a fixed line break instead of %n like \r\n (Windows).

2 of 2
0

Initialization of input stream will remove file content, so you can read file content first, and then write to it as following:

public static void main(String[] args) throws FileNotFoundException {
        boolean foundException = false;
        Scanner keyboard = new Scanner(System.in);
        do {
            try {
                System.out.print("Please enter input file name: ");
                String fileName = keyboard.next();
                File inputFile = new File("inputfile.txt");
                Scanner scanner = new Scanner(new File("inputfile.txt"));
                ArrayList<String> lines = new ArrayList<>();

                int lineNum = 1;
                while (scanner.hasNextLine()) {
                    String line = scanner.nextLine();
                    line = line.trim();
                    if (line.length() > 0) {
                        lines.add(lineNum + "." + line);
                        lineNum++;
                    }
                }
                PrintStream out = new PrintStream(new File("inputfile.txt"));
                for (String line : lines)
                    out.println(line);

            } catch (FileNotFoundException x) {
                System.out.println("File does not exist");
                foundException = true;
            }

        } while (foundException);
    }

And method name called on file object does not return number of lines in file. I will refer to docs:

The length, in bytes, of the file denoted by this abstract pathname, or 0L if the file does not exist. Some operating systems may return 0L for pathnames denoting system-dependent entities such as devices or pipes.

๐ŸŒ
Java-tips
java-tips.org โ€บ home โ€บ java se tips โ€บ java.io โ€บ insert a line in a file
Insert a line in a file - Java Tips
The only way to insert a line in a text file is to read the original file and write the content in a temporary file with the new line inserted.
๐ŸŒ
Java67
java67.com โ€บ 2015 โ€บ 07 โ€บ how-to-append-text-to-existing-file-in-java-example.html
How to append text to existing File in Java? Example | Java67
That's all about how to append text into an existing file in Java. You can use FileWriter to open the file for appending text as opposed to writing text. The difference between them is that when you append data, it will be added at the end of the file. Since FileWriter writes one character at a time, it's better to use BufferedWriter class for efficient writing. You can also use PrintWriter if you want to use its convenient print() and println() method for writing lines into the file but it's not necessary to write text at the end of the file.
๐ŸŒ
Blogger
javarevisited.blogspot.com โ€บ 2012 โ€บ 12 โ€บ how-to-append-text-into-file-in-java-filewriter-example.html
How to append text into File in Java โ€“ FileWriter Example
Here is another example of appending text to a file in Java, it also uses FileWriter class but with PrintWriter to append text line by line.
Top answer
1 of 2
1

May not be the best way, but works!

First Delete the line

File inputFile = new File("test.txt");
File tempFile = new File("myTempFile.txt");

BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));

String lineToRemove = "I joined Stackoverflow today.";
String currentLine;

while((currentLine = reader.readLine()) != null) {
// trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)) continue;
writer.write(currentLine + System.getProperty("line.separator"));
}
boolean successful = tempFile.renameTo(inputFile);
writer.close(); 
reader.close(); 

Then Append it at the beginning of your file

RandomAccessFile f = new RandomAccessFile(new File("yourtextfile.txt"), "rw");
f.seek(0); // to the beginning
f.write(lineToRemove.getBytes());
f.close();
2 of 2
0

the input file being used has duplicates records DETAILS: aa bb aa gg bb bb

To remove duplicates, I am using the following code

File Readfile= new File(n.getProperty("file"));
BufferedReader reader= new BufferedReader(new FileReader(Readfile));
Set<String> lines = new HashSet<String>(10000);
String line;
while((line=reader.readLine())!=null){
    lines.add(line);
}
reader.close();
File file =new File("stripduplicates.txt");

if(!file.exists()){
    file.createNewFile();
}
BufferedWriter writer = new BufferedWriter(new FileWriter(file.getPath()));
   //EDIT done
    writer.write("DETAILS:");
for(String unique: lines){
    //EDIT done
      if(!(unique.startsWith("DETAILS:"))
        {
        writer.write(unique);
        writer.newLine();
        }
}
writer.close();
}

The output is coming as needed

DETAILS: aa gg bb