简体   繁体   中英

How to append a new line to beginning of an existing file in java?

Assuming I have a txt file located in /mypath/sampletext.txt. How do I append a new line to the beginning of the file with the following in Java while preserving the original text file's contents?:

String startStr ="--Start of File--";

Looking for a way to do this without having to create an intermediary 2nd file and make modifications only to the existing file if possible.

首先读取文件内容,在contents = newLine + contents类前添加新行,然后将新contents = newLine + contents写入同一文件中(不要添加)。

well,three ways ,may help you

1.

//true: is append text to fie FileWriter write = new FileWriter("file_path",true); writer.write(content);

  1. //open randomFile and "rw"
    randomFile = new RandomAccessFile("file_path", "rw");
    // file length
    long fileLength = randomFile.length();
    //point to end index randomFile.seek(fileLength);
    //write randomFile.writeBytes(content);

  2. BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)));
    out.write(conent);

New answer is updated...

In this I've use few more FileIO classes & may be their one is deprecated API but If you are aware with Java FileIO classes you can easily fix it.

Here I append new line at the start of file rather than append it to the end of file..

If any issue please comment again....

Try this, I think it will help you..

try
    {
        //Append new line in existing file.
        FileInputStream fr = new FileInputStream("onlineSoultion.txt");
        DataInputStream dr = new DataInputStream(fr);

        String startStr = "--Start of File--\n";
        //String startStr;

        while (dr.available() > 0) {
            startStr += dr.readLine();
            //System.out.println(startStr);
        }
        dr.close();
        fr.close();

        FileOutputStream writer = new FileOutputStream("onlineSoultion.txt");
        writer.write((new String()).getBytes());
        writer.close();

        PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("onlineSoultion.txt", true)));
        out.println(startStr);
        out.close();

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM