Java. How to append text to top of file.txt [duplicate]
Asked Answered
V

3

26

I need to add text to beggining of text file via Java.

For example I have test.txt file with data:

Peter
John
Alice

I need to add(to top of file):

Jennifer 

It should be:

Jennifer
Peter
John
Alice

I have part of code, but It append data to end of file, I need to make It that added text to top of file:

    public static void irasymas(String irasymai){
        try {
         File file = new File("src/lt/test.txt");

                if (!file.exists()) {
                file.createNewFile();
            }

            FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(irasymai+ "\r\n");
            bw.close();
} 
       catch (IOException e) {
        e.printStackTrace();                
        }
    }

I have tried this, but this only deletes all data from file and not insert any text:

public static void main(String[] args) throws IOException {
        BufferedReader reader = null;
        BufferedWriter writer = null;
        ArrayList list = new ArrayList();

        try {
            reader = new BufferedReader(new FileReader("src/lt/test.txt"));
            String tmp;
            while ((tmp = reader.readLine()) != null)
                list.add(tmp);
            OUtil.closeReader(reader);

            list.add(0, "Start Text");
            list.add("End Text");

            writer = new BufferedWriter(new FileWriter("src/lt/test.txt"));
            for (int i = 0; i < list.size(); i++)
                writer.write(list.get(i) + "\r\n");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            OUtil.closeReader(reader);
            OUtil.closeWriter(writer);
        }
    }

Thank you for help.

Viaduct answered 21/5, 2013 at 8:11 Comment(3)
Is it needed to use the ArrayList?@Rimantė BaltiejūtėNureyev
I don't think so, I just posted 1 of many solutions what I have tried.Viaduct
Read my code and see if it is useful :DNureyev
A
-3

You can use RandomAccessFile to and seek the cursor to 0th position using seek(long position) method, before starting to write.

As explained in this thread

RandomAccessFile f = new RandomAccessFile(new File("yourFile.txt"), "rw");
f.seek(0); // to the beginning
f.write("Jennifer".getBytes());
f.close();

Edit: As pointed out below by many comments, this solution overwrites the file content from beginning. To completely replace the content, the File may have to be deleted and re-written.

Argosy answered 21/5, 2013 at 8:11 Comment(10)
Thank you for answer. I have been tried RandomAccessFile, but unsuccessfuly. Could you help me with It a little bit, please?Viaduct
And what is "rw" here?Viaduct
rw is a mode. That means you are opening the file to both r - read w - write. for your need w is enough, because you are only writing.Argosy
Thank you for code, but this working incorrect. It not appeding, but deleting first line. If my file looks like 111 222 333 444 after I use this code It adding "Jennifer" to top of file, but It looks like: Jennifer22 333 444 First line deleted and 2nd line half deleted.Viaduct
See docs.oracle.com/javase/tutorial/essential/io/rafs.htmlArgosy
Is this code overwriting or inserting?Stereochromy
Overwriting first Line.Viaduct
This code doesn't work. It actually replaces existing bytes in the file, not inserts.Avocado
THE ANSWER IS WRONG!!!Tamtam
The answer is not correct because the RandomAccessFile would overwrite the current content of the file from position where f.seek(position); Better to convert the file into String and do String manipulationClepsydra
N
5
File mFile = new File("src/lt/test.txt");
FileInputStream fis = new FileInputStream(mFile);
BufferedReader br = new BufferedReader(fis);
String result = "";
String line = "";
while( (line = br.readLine()) != null){
 result = result + line; 
}

result = "Jennifer" + result;

mFile.delete();
FileOutputStream fos = new FileOutputStream(mFile);
fos.write(result.getBytes());
fos.flush();

The idea is read it all, add the string in the front. Delete old file. Create the new file with eited String.

Nureyev answered 21/5, 2013 at 8:34 Comment(4)
Thank you for answer, but in this line BufferedReader br = new BufferedReader(fis); I got error: The Constructor BufferedReader(FileInputStream) is undefined.Viaduct
@Rimantė Baltiejūtė Sorry missing something BufferecReader(new InputStreamReader(new FileInputStream()))Nureyev
Please use StingBufferLalise
You should fix example to new BufferedReader(new InputStreamReaderPilsner
A
-3

You can use RandomAccessFile to and seek the cursor to 0th position using seek(long position) method, before starting to write.

As explained in this thread

RandomAccessFile f = new RandomAccessFile(new File("yourFile.txt"), "rw");
f.seek(0); // to the beginning
f.write("Jennifer".getBytes());
f.close();

Edit: As pointed out below by many comments, this solution overwrites the file content from beginning. To completely replace the content, the File may have to be deleted and re-written.

Argosy answered 21/5, 2013 at 8:11 Comment(10)
Thank you for answer. I have been tried RandomAccessFile, but unsuccessfuly. Could you help me with It a little bit, please?Viaduct
And what is "rw" here?Viaduct
rw is a mode. That means you are opening the file to both r - read w - write. for your need w is enough, because you are only writing.Argosy
Thank you for code, but this working incorrect. It not appeding, but deleting first line. If my file looks like 111 222 333 444 after I use this code It adding "Jennifer" to top of file, but It looks like: Jennifer22 333 444 First line deleted and 2nd line half deleted.Viaduct
See docs.oracle.com/javase/tutorial/essential/io/rafs.htmlArgosy
Is this code overwriting or inserting?Stereochromy
Overwriting first Line.Viaduct
This code doesn't work. It actually replaces existing bytes in the file, not inserts.Avocado
THE ANSWER IS WRONG!!!Tamtam
The answer is not correct because the RandomAccessFile would overwrite the current content of the file from position where f.seek(position); Better to convert the file into String and do String manipulationClepsydra
C
-3

The below code worked for me. Again it will obviously replace the bytes at the beginning of the file. If you can certain how many bytes of replacement will be done in advance then you can use this. Otherwise, follow the earlier answers or take a look at here Writing in the beginning of a text file Java

    String str = "Jennifer";  
    byte data[] = str.getBytes();       

    try {                           
            RandomAccessFile f = new RandomAccessFile(new File("src/lt/test.txt"), "rw");
            f.getChannel().position(0);         
            f.write(data);
            f.close();
    } catch (IOException e) {       
            e.printStackTrace();
    }
Chub answered 20/12, 2013 at 3:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.