如何将文本附加到Java中的现有文件中

时间:2009-10-26 14:43:50

标签: java file-io io text-files

我需要将文本重复附加到Java中的现有文件中。我该怎么做?

31 个答案:

答案 0 :(得分:742)

您是否正在执行此操作以进行日志记录?如果是,则有several libraries for this。其中两个最受欢迎的是Log4jLogback

Java 7 +

如果您只需要这样做一次,Files class就可以轻松完成:

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。它也不会自动附加换行符(当您追加到文本文件时通常需要它)。 Steve Chambers's answer介绍了如何使用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语法。
  • BufferedWriterPrintWriter包装并非绝对必要。

旧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
    }
}

答案 1 :(得分:158)

您可以将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());
}

答案 2 :(得分:66)

这里使用try / catch块的所有答案都不应该包含finally块中的.close()吗?

标记答案的示例:

PrintWriter out = null;
try {
    out = new PrintWriter(new BufferedWriter(new FileWriter("writePath", true)));
    out.println("the text");
} catch (IOException e) {
    System.err.println(e);
} finally {
    if (out != null) {
        out.close();
    }
} 

此外,从Java 7开始,您可以使用try-with-resources statement。关闭声明的资源不需要finally块,因为它是自动处理的,并且也不那么详细:

try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("writePath", true)))) {
    out.println("the text");
} catch (IOException e) {
    System.err.println(e);
}

答案 3 :(得分:40)

编辑 - 从Apache Commons 2.1开始,正确的方法是:

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

我改编了@Kip的解决方案,包括最终正确关闭文件:

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

答案 4 :(得分:24)

稍微扩展Kip's answer, 这是一个简单的Java 7+方法,用于将新行附加到文件中,创建它(如果它尚不存在)

try {
    final Path path = Paths.get("path/to/filename.txt");
    Files.write(path, Arrays.asList("New line to append"), StandardCharsets.UTF_8,
        Files.exists(path) ? StandardOpenOption.APPEND : StandardOpenOption.CREATE);
} catch (final IOException ioe) {
    // Add your own exception handling...
}

注意:以上使用Files.write重载将文本的写入文件(即类似于println命令)。要仅将文本写入末尾(即类似于print命令),可以使用替代Files.write重载,传入字节数组(例如"mytext".getBytes(StandardCharsets.UTF_8))。

答案 5 :(得分:21)

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

有些警告,如果出现错误,这些答案中有多少会使文件句柄保持打开状态。答案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.
  }

答案 6 :(得分:13)

在Java-7中也可以这样做:

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

// ---------------------

Path filePath = Paths.get("someFile.txt");
if (!Files.exists(filePath)) {
    Files.createFile(filePath);
}
Files.write(filePath, "Text to be added".getBytes(), StandardOpenOption.APPEND);

答案 7 :(得分:8)

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 到现有文件。使用它,可以避免在类路径中添加不必要的库。

答案 8 :(得分:7)

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

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

答案 9 :(得分:6)

使用java.nio。Files和java.nio.file。StandardOpenOption

    PrintWriter out = null;
    BufferedWriter bufWriter;

    try{
        bufWriter =
            Files.newBufferedWriter(
                Paths.get("log.txt"),
                Charset.forName("UTF8"),
                StandardOpenOption.WRITE, 
                StandardOpenOption.APPEND,
                StandardOpenOption.CREATE);
        out = new PrintWriter(bufWriter, true);
    }catch(IOException e){
        //Oh, no! Failed to create PrintWriter
    }

    //After successful creation of PrintWriter
    out.println("Text to be appended");

    //After done writing, remember to close!
    out.close();

这将使用文件创建BufferedWriter,该文件接受StandardOpenOption参数,并从结果PrintWriter创建自动刷新BufferedWriter。然后可以调用PrintWriter的{​​{1}}方法来写入文件。

此代码中使用的println()参数:打开要写入的文件,仅附加到文件,如果文件不存在则创建该文件。

StandardOpenOption可以替换为Paths.get("path here")。 可以修改new File("path here").toPath()以适应所需的Charset.forName("charset name")

答案 10 :(得分:5)

我只是添加小细节:

    new FileWriter("outfilename", true)

2.nd参数(true)是一个名为可附加http://docs.oracle.com/javase/7/docs/api/java/lang/Appendable.html)的功能(或界面)。它负责能够将某些内容添加到特定文件/流的末尾。此接口从Java 1.5开始实现。具有此接口的每个对象(即 BufferedWriter,CharArrayWriter,CharBuffer,FileWriter,FilterWriter,LogStream,OutputStreamWriter,PipedWriter,PrintStream,PrintWriter,StringBuffer,StringBuilder,StringWriter,Writer )都可用于添加内容

换句话说,您可以向gzip压缩文件或某些http进程

添加一些内容

答案 11 :(得分:5)

示例,使用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);
}

答案 12 :(得分:4)

尝试使用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);
}

答案 13 :(得分:3)

最好使用try-with-resources,然后使用java 7之前的所有业务

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

答案 14 :(得分:3)

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

这将做你想要的......

答案 15 :(得分:3)

如果我们使用Java 7及更高版本并且还知道要添加(附加)到文件的内容,我们可以在NIO包中使用newBufferedWriter方法。

public static void main(String[] args) {
    Path FILE_PATH = Paths.get("C:/temp", "temp.txt");
    String text = "\n Welcome to Java 8";

    //Writing to the file temp.txt
    try (BufferedWriter writer = Files.newBufferedWriter(FILE_PATH, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) {
        writer.write(text);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

有几点需要注意:

  1. 指定字符集编码总是一个好习惯,为此我们在课程StandardCharsets中保持不变。
  2. 代码使用try-with-resource语句,其中资源在尝试后自动关闭。
  3. 虽然OP没有询问,但是我们想要搜索具有某些特定关键字的行,例如confidential我们可以在Java中使用流API:

    //Reading from the file the first line which contains word "confidential"
    try {
        Stream<String> lines = Files.lines(FILE_PATH);
        Optional<String> containsJava = lines.filter(l->l.contains("confidential")).findFirst();
        if(containsJava.isPresent()){
            System.out.println(containsJava.get());
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    

答案 16 :(得分:3)

680012345678976|aIDrLVvFqHXDzl6538RLUF4S9C4

答案 17 :(得分:2)

在项目的任何位置创建一个函数,只需在需要的地方调用该函数。

你要记住,你们要记住你们正在调用活动线程而不是异步调用,因为它可能是一个好的5到10页才能正确完成。 为什么不在你的项目上花更多的时间而忘记写任何已写的东西。 适当

    //Adding a static modifier would make this accessible anywhere in your app

    public Logger getLogger()
    {
       return java.util.logging.Logger.getLogger("MyLogFileName");
    }
    //call the method anywhere and append what you want to log 
    //Logger class will take care of putting timestamps for you
    //plus the are ansychronously done so more of the 
    //processing power will go into your application

    //from inside a function body in the same class ...{...

    getLogger().log(Level.INFO,"the text you want to append");

    ...}...
    /*********log file resides in server root log files********/

三行代码2真的是因为第三行实际附加了文本。 :P

答案 18 :(得分:2)

  

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

代码

public void append()
{
    try
    {
        String path = "D:/sample.txt";

        File file = new File(path);

        FileWriter fileWriter = new FileWriter(file,true);

        BufferedWriter bufferFileWriter  = new BufferedWriter(fileWriter);

        fileWriter.append("Sample text in the file to append");

        bufferFileWriter.close();

        System.out.println("User Registration Completed");

    }catch(Exception ex)
    {
        System.out.println(ex);
    }
}

答案 19 :(得分:2)

你也可以试试这个:

JFileChooser c= new JFileChooser();
c.showOpenDialog(c);
File write_file = c.getSelectedFile();
String Content = "Writing into file"; //what u would like to append to the file



try 
{
    RandomAccessFile raf = new RandomAccessFile(write_file, "rw");
    long length = raf.length();
    //System.out.println(length);
    raf.setLength(length + 1); //+ (integer value) for spacing
    raf.seek(raf.length());
    raf.writeBytes(Content);
    raf.close();
} 
catch (Exception e) {
    //any exception handling method of ur choice
}

答案 20 :(得分:2)

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

    stream.write(

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

    );

} finally {
    stream.close();
}

然后在上游某处捕获IOException。

答案 21 :(得分:2)

FileOutputStream fos = new FileOutputStream("File_Name", true);
fos.write(data);

true允许将数据附加到现有文件中。如果我们写的话

FileOutputStream fos = new FileOutputStream("File_Name");

它将覆盖现有文件。所以先采取行动。

答案 22 :(得分:1)

以下方法让您将文本附加到某个文件:

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

效率不高但工作正常。正确处理换行符并创建一个新文件(如果尚未存在)。

答案 23 :(得分:1)

此代码可满足您的需求:

Invoice_Discount_Type | Invoice_Discount
----------------------------------------
null                  | null
84                    | 750
84                    | 1500
144                   | 7
0                     | 25
144                   | 2
0                     | 16
---------------------------------------

答案 24 :(得分:1)

我可能会建议apache commons project。该项目已经提供了一个框架,可以满足您的需求(即灵活过滤集合)。

答案 25 :(得分:1)

如果您想在特定线路中添加某些文本,您可以先读取整个文件,在任意位置附加文本,然后覆盖以下代码中的所有内容:

public static void addDatatoFile(String data1, String data2){


    String fullPath = "/home/user/dir/file.csv";

    File dir = new File(fullPath);
    List<String> l = new LinkedList<String>();

    try (BufferedReader br = new BufferedReader(new FileReader(dir))) {
        String line;
        int count = 0;

        while ((line = br.readLine()) != null) {
            if(count == 1){
                //add data at the end of second line                    
                line += data1;
            }else if(count == 2){
                //add other data at the end of third line
                line += data2;
            }
            l.add(line);
            count++;
        }
        br.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }       
    createFileFromList(l, dir);
}

public static void createFileFromList(List<String> list, File f){

    PrintWriter writer;
    try {
        writer = new PrintWriter(f, "UTF-8");
        for (String d : list) {
            writer.println(d.toString());
        }
        writer.close();             
    } catch (FileNotFoundException | UnsupportedEncodingException e) {
        e.printStackTrace();
    }
}

答案 26 :(得分:0)

对于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对象。

答案 27 :(得分:0)

/**********************************************************************
 * it will write content to a specified  file
 * 
 * @param keyString
 * @throws IOException
 *********************************************************************/
public static void writeToFile(String keyString,String textFilePAth) throws IOException {
    // For output to file
    File a = new File(textFilePAth);

    if (!a.exists()) {
        a.createNewFile();
    }
    FileWriter fw = new FileWriter(a.getAbsoluteFile(), true);
    BufferedWriter bw = new BufferedWriter(fw);
    bw.append(keyString);
    bw.newLine();
    bw.close();
}// end of writeToFile()

答案 28 :(得分:0)

我的回答:

Dim ws                    As Worksheet
Dim DateValues            As Range
Dim Shortfall             As Range
Dim Region                As Range
Dim Bucket                As Range
Dim Shortfall_rng         As Range
Dim Region_rng            As Range
Dim Bucket_rng            As Range
Dim Datevalues_rng        As Range
Dim estring               As Variant
Dim StartCopying          As Range

Set ws = Worksheets("Asia_All")

Set StartCopying = ws.Range("O4")

Set Region = ws.Range("O1")    ' Value in cell O1 is "New York" (without Quotes)
Set Bucket = ws.Range("O2")    ' Value in cell O2 is "<!--1-->0 - 1" (without Quotes)
Set DateValues = ws.Range("O3")    ' Value in cell O3 is "2007-01-02" (without Quotes)



Set Shortfall_rng = ws.Range("$B$2:$B$142411")
Set Bucket_rng = ws.Range("$F$2:$F$142411")
Set Datevalues_rng = ws.Range("J$2:$J$142411")
Set Region_rng = ws.Range("$K$2:$K$142411")


estring = ws.Evaluate("Index(" & Shortfall_rng.Address & ", Match(" & Bucket.Address & "&" & Region.Address & "&" & DateValues.Address & ", " & Bucket_rng.Address & " & " & Region_rng.Address & "&" & Datevalues_rng.Address & ", 0))")

StartCopying.Value = estring

答案 29 :(得分:-1)

您可以使用follong代码将内容附加到文件中:

 String fileName="/home/shriram/Desktop/Images/"+"test.txt";
  FileWriter fw=new FileWriter(fileName,true);    
  fw.write("here will be you content to insert or append in file");    
  fw.close(); 
  FileWriter fw1=new FileWriter(fileName,true);    
 fw1.write("another content will be here to be append in the same file");    
 fw1.close(); 

答案 30 :(得分:-2)

1.7方法:

void appendToFile(String filePath, String content) throws IOException{

    Path path = Paths.get(filePath);

    try (BufferedWriter writer = 
            Files.newBufferedWriter(path, 
                    StandardOpenOption.APPEND)) {
        writer.newLine();
        writer.append(content);
    }

    /*
    //Alternative:
    try (BufferedWriter bWriter = 
            Files.newBufferedWriter(path, 
                    StandardOpenOption.WRITE, StandardOpenOption.APPEND);
            PrintWriter pWriter = new PrintWriter(bWriter)
            ) {
        pWriter.println();//to have println() style instead of newLine();   
        pWriter.append(content);//Also, bWriter.append(content);
    }*/
}