如何在java中向现有文件追加文本?

oiopk7p5  于 2021-07-04  发布在  Java
关注(0)|答案(31)|浏览(613)

我需要在java中重复地向现有文件追加文本。我该怎么做?

sshcrbum

sshcrbum16#

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class Writer {

    public static void main(String args[]){
        doWrite("output.txt","Content to be appended to file");
    }

    public static void doWrite(String filePath,String contentToBeAppended){

       try(
            FileWriter fw = new FileWriter(filePath, true);
            BufferedWriter bw = new BufferedWriter(fw);
            PrintWriter out = new PrintWriter(bw)
          )
          {
            out.println(contentToBeAppended);
          }  
        catch( IOException e ){
        // File writing/opening failed at some stage.
        }

    }

}
tkclm6bt

tkclm6bt17#

使用以下方法可以将文本附加到某个文件:

private void appendToFile(String filePath, String text)
{
    PrintWriter fileWriter = null;

    try
    {
        fileWriter = new PrintWriter(new BufferedWriter(new FileWriter(
                filePath, true)));

        fileWriter.println(text);
    } catch (IOException ioException)
    {
        ioException.printStackTrace();
    } finally
    {
        if (fileWriter != null)
        {
            fileWriter.close();
        }
    }
}

交替使用 FileUtils :

public static void appendToFile(String filePath, String text) throws IOException
{
    File file = new File(filePath);

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

    String fileContents = FileUtils.readFileToString(file);

    if(file.length() != 0)
    {
        fileContents = fileContents.concat(System.lineSeparator());
    }

    fileContents = fileContents.concat(text);

    FileUtils.writeStringToFile(file, fileContents);
}

效率不高,但效果很好。换行符处理正确,如果还不存在新文件,则会创建一个新文件。

llew8vvj

llew8vvj18#

我可以建议使用apachecommons项目。这个项目已经提供了一个框架来完成您需要的工作(即灵活地筛选集合)。

b4lqfgs4

b4lqfgs419#

这可以在一行代码中完成。希望这有帮助:)

Files.write(Paths.get(fileName), msg.getBytes(), StandardOpenOption.APPEND);
eqfvzcg8

eqfvzcg820#

String str;
    String path = "C:/Users/...the path..../iin.txt"; // you can input also..i created this way :P

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    PrintWriter pw = new PrintWriter(new FileWriter(path, true));

    try 
    {
       while(true)
        {
            System.out.println("Enter the text : ");
            str = br.readLine();
            if(str.equalsIgnoreCase("exit"))
                break;
            else
                pw.println(str);
        }
    } 
    catch (Exception e) 
    {
        //oh noes!
    }
    finally
    {
        pw.close();         
    }

这会达到你的目的。。

pcrecxhr

pcrecxhr21#

确保流在所有情况下都正确关闭。

如果出现错误,这些答案中有多少会让文件句柄保持打开状态,这有点令人震惊。答案https://stackoverflow.com/a/15053443/2498188 在钱上但只是因为 BufferedWriter() 不能扔。如果可以的话,一个例外就会离开 FileWriter 对象打开。
一种更为普遍的方法 BufferedWriter() 可以投掷:

PrintWriter out = null;
  BufferedWriter bw = null;
  FileWriter fw = null;
  try{
     fw = new FileWriter("outfilename", true);
     bw = new BufferedWriter(fw);
     out = new PrintWriter(bw);
     out.println("the text");
  }
  catch( IOException e ){
     // File writing/opening failed at some stage.
  }
  finally{
     try{
        if( out != null ){
           out.close(); // Will close bw and fw too
        }
        else if( bw != null ){
           bw.close(); // Will close fw too
        }
        else if( fw != null ){
           fw.close();
        }
        else{
           // Oh boy did it fail hard! :3
        }
     }
     catch( IOException e ){
        // Closing the file writers failed for some obscure reason
     }
  }

编辑:

从java 7开始,推荐的方法是使用“try with resources”并让jvm处理它:

try(    FileWriter fw = new FileWriter("outfilename", true);
          BufferedWriter bw = new BufferedWriter(fw);
          PrintWriter out = new PrintWriter(bw)){
     out.println("the text");
  }  
  catch( IOException e ){
      // File writing/opening failed at some stage.
  }
plicqrtu

plicqrtu22#

你这样做是为了记录吗?如果是这样的话,有好几个库可以用来做这个。两个最流行的是log4j和logback。

java 7+

如果您只需要执行一次,则files类会使此操作变得简单:

try {
    Files.write(Paths.get("myfile.txt"), "the text".getBytes(), StandardOpenOption.APPEND);
}catch (IOException e) {
    //exception handling left as an exercise for the reader
}

小心:以上方法会抛出 NoSuchFileException 如果文件不存在。它也不会自动追加换行符(追加到文本文件时通常需要这样做)。史蒂夫·钱伯斯的回答涵盖了你如何利用 Files 班级。
但是,如果要多次写入同一个文件,则必须多次打开和关闭磁盘上的文件,这是一个缓慢的操作。在这种情况下,缓冲写入程序更好:

try(FileWriter fw = new FileWriter("myfile.txt", true);
    BufferedWriter bw = new BufferedWriter(fw);
    PrintWriter out = new PrintWriter(bw))
{
    out.println("the text");
    //more code
    out.println("more text");
    //more code
} catch (IOException e) {
    //exception handling left as an exercise for the reader
}

笔记:
第二个参数 FileWriter 构造函数将告诉它附加到文件中,而不是编写新文件(如果文件不存在,将创建该文件。)
使用 BufferedWriter 推荐给昂贵的作家(如 FileWriter ).
使用 PrintWriter 允许您访问 println 你可能习惯的语法 System.out .
但是 BufferedWriter 以及 PrintWriter Package 纸不是绝对必要的。

旧版java

try {
    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("myfile.txt", true)));
    out.println("the text");
    out.close();
} catch (IOException e) {
    //exception handling left as an exercise for the reader
}

异常处理

如果您需要对旧版java进行健壮的异常处理,它会变得非常冗长:

FileWriter fw = null;
BufferedWriter bw = null;
PrintWriter out = null;
try {
    fw = new FileWriter("myfile.txt", true);
    bw = new BufferedWriter(fw);
    out = new PrintWriter(bw);
    out.println("the text");
    out.close();
} catch (IOException e) {
    //exception handling left as an exercise for the reader
}
finally {
    try {
        if(out != null)
            out.close();
    } catch (IOException e) {
        //exception handling left as an exercise for the reader
    }
    try {
        if(bw != null)
            bw.close();
    } catch (IOException e) {
        //exception handling left as an exercise for the reader
    }
    try {
        if(fw != null)
            fw.close();
    } catch (IOException e) {
        //exception handling left as an exercise for the reader
    }
}
qlzsbp2j

qlzsbp2j23#

java 7+
在我看来,由于我是纯java的粉丝,我建议将上述答案结合起来。也许我参加聚会迟到了。代码如下:

String sampleText = "test" +  System.getProperty("line.separator");
 Files.write(Paths.get(filePath), sampleText.getBytes(StandardCharsets.UTF_8), 
 StandardOpenOption.CREATE, StandardOpenOption.APPEND);

如果文件不存在,它会创建它,如果已经存在,它会将sampletext附加到现有文件中。使用它,可以避免向类路径添加不必要的lib。

ql3eal8s

ql3eal8s24#

编辑-从apache commons 2.1开始,正确的方法是:

FileUtils.writeStringToFile(file, "String to append", true);

我修改了@kip的解决方案,包括在finally上正确关闭文件:

public static void appendToFile(String targetFile, String s) throws IOException {
    appendToFile(new File(targetFile), s);
}

public static void appendToFile(File targetFile, String s) throws IOException {
    PrintWriter out = null;
    try {
        out = new PrintWriter(new BufferedWriter(new FileWriter(targetFile, true)));
        out.println(s);
    } finally {
        if (out != null) {
            out.close();
        }
    }
}
sxpgvts3

sxpgvts325#

试试bufferfilewriter.append,它适合我。

FileWriter fileWriter;
try {
    fileWriter = new FileWriter(file,true);
    BufferedWriter bufferFileWriter = new BufferedWriter(fileWriter);
    bufferFileWriter.append(obj.toJSONString());
    bufferFileWriter.newLine();
    bufferFileWriter.close();
} catch (IOException ex) {
    Logger.getLogger(JsonTest.class.getName()).log(Level.SEVERE, null, ex);
}
vs3odd8k

vs3odd8k26#

对于jdk版本>=7
您可以使用此简单方法将给定内容附加到指定文件:

void appendToFile(String filePath, String content) {
  try (FileWriter fw = new FileWriter(filePath, true)) {
    fw.write(content + System.lineSeparator());
  } catch (IOException e) { 
    // TODO handle exception
  }
}

我们正在以追加模式构造filewriter对象。

f1tvaqid

f1tvaqid27#

你可以用 fileWriter 旗设为 true ,用于附加。

try
{
    String filename= "MyFile.txt";
    FileWriter fw = new FileWriter(filename,true); //the true will append the new data
    fw.write("add a line\n");//appends the string to the file
    fw.close();
}
catch(IOException ioe)
{
    System.err.println("IOException: " + ioe.getMessage());
}
cetgtptt

cetgtptt28#

FileOutputStream stream = new FileOutputStream(path, true);
try {

    stream.write(

        string.getBytes("UTF-8") // Choose your encoding.

    );

} finally {
    stream.close();
}

然后在上游某个地方捕获一个ioexception。

pokxtpni

pokxtpni29#

最好使用try with resources,而不是所有Java7之前的业务

static void appendStringToFile(Path file, String s) throws IOException  {
    try (BufferedWriter out = Files.newBufferedWriter(file, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) {
        out.append(s);
        out.newLine();
    }
}
z4iuyo4d

z4iuyo4d30#

样本,使用Guava:

File to = new File("C:/test/test.csv");

for (int i = 0; i < 42; i++) {
    CharSequence from = "some string" + i + "\n";
    Files.append(from, to, Charsets.UTF_8);
}

相关问题