简体   繁体   English

如何在Java中现有文件的开头添加新行?

[英]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. 假设我在/mypath/sampletext.txt中有一个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?: 在保留原始文本文件内容的同时,如何在Java中用以下内容在文件开头添加新行?

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. 1。

//true: is append text to fie FileWriter write = new FileWriter("file_path",true); // true:将文本追加到fie FileWriter中write = new FileWriter(“ file_path”,true); writer.write(content); writer.write(内容);

  1. //open randomFile and "rw" //打开randomFile和“ rw”
    randomFile = new RandomAccessFile("file_path", "rw"); randomFile =新的RandomAccessFile(“ file_path”,“ rw”);
    // file length //文件长度
    long fileLength = randomFile.length(); 长文件长度= randomFile.length();
    //point to end index randomFile.seek(fileLength); //指向结束索引randomFile.seek(fileLength);
    //write randomFile.writeBytes(content); // write randomFile.writeBytes(content);

  2. BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true))); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file,true)));
    out.write(conent); 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. 在本文中,我使用了几个FileIO类,并且可能是其中的一个不推荐使用的API,但是如果您了解Java FileIO类,则可以轻松对其进行修复。

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

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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