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

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

你是做这个logging的目的? 如果是这样的话,有几个库 。 其中两个最stream行的是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类来做到这一点。

但是,如果你多次写入同一个文件,上面的操作会多次打开和closures磁盘上的文件,这是一个缓慢的操作。 在这种情况下,缓冲的作家是更好的:

 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构造函数的第二个参数将告诉它附加到文件,而不是写入一个新文件。 (如果文件不存在,它将被创build。)
  • 对于昂贵的作家(如FileWriter ),build议使用BufferedWriter
  • 使用PrintWriter可以访问你可能从System.out使用的println语法。
  • 但是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 } 

exception处理

如果您需要对较旧的Java进行强大的exception处理,则它会变得非常冗长:

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

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

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语句 。 closures声明的资源不需要finally块,因为它是自动处理的,也不那么冗长:

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

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

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

我修改了@Kip的解决scheme,包括正确地closures文件:

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

确保在所有情况下都能正确closuresstream。

如果出现错误,这些答案中有多less会使文件句柄保持打开状态有点令人担忧。 答案https://stackoverflow.com/a/15053443/2498188是在钱上,但只是因为;BufferedWriter()不能抛出。 如果可以的话,一个exception会使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开始,推荐的方法是使用“尝试使用资源”并让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. } 

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

样品,使用番石榴:

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

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

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

我只是添加小细节:

  new FileWriter("outfilename", true) 

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

换句话说,你可以添加一些内容到你的gzip文件,或者一些http进程

使用java.nio。 文件以及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(); 

这将使用Files创build一个BufferedWriter ,该文件接受StandardOpenOption参数,并从生成的BufferedWriter自动刷新PrintWriterPrintWriterprintln()方法可以被调用来写入文件。

此代码中使用的StandardOpenOption参数:打开文件进行写入,只附加到文件,并创build文件(如果文件不存在)。

Paths.get("path here")可以被new File("path here").toPath()replace为new File("path here").toPath() 。 和Charset.forName("charset name")可以被修改,以适应所需的Charset

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

要稍微扩展Kip的答案 ,下面是一个简单的Java 7+方法,用于在文件中添加新行如果尚不存在 ,则创build该

 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) )。

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

这将做你想要的

如果我们使用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语句,其中资源在try之后自动closures。

虽然OP没有问,但是如果我们想要search具有特定关键字的行,例如confidential我们可以利用Java中的streamAPI:

 //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(); } 
 FileOutputStream stream = new FileOutputStream(path, true); try { stream.write( string.getBytes("UTF-8") // Choose your encoding. ); } finally { stream.close(); } 

然后在上游的某处发现IOException。

在你的项目的任何地方创build一个函数,只要你需要的地方调用这个函数。

你必须记住,你们正在调用你不是asynchronous调用的活动线程,因为它可能是一个好的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

图书馆

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

你也可以试试这个:

 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 } 

最好是使用try-with-resources,然后是所有那些pre-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(); } } 

此代码将满足您的需求:

  FileWriter fw=new FileWriter("C:\\file.json",true); fw.write("ssssss"); fw.close(); 
 FileOutputStream fos = new FileOutputStream("File_Name", true); fos.write(data); 

true允许在现有文件中追加数据。 如果我们会写

 FileOutputStream fos = new FileOutputStream("File_Name"); 

它会覆盖现有的文件。 所以去第一个方法。

我可能会build议apache commons项目 。 这个项目已经提供了一个框架来做你需要的东西(比如灵活的collections过滤)。

下面的方法让你将文本附加到某个文件中:

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

它效率不高,但工作正常。 换行符正确处理,并创build一个新的文件,如果还不存在。

我的答案:

 JFileChooser chooser= new JFileChooser(); chooser.showOpenDialog(chooser); File file = chooser.getSelectedFile(); String Content = "What you want to append to file"; try { RandomAccessFile random = new RandomAccessFile(file, "rw"); long length = random.length(); random.setLength(length + 1); random.seek(random.length()); random.writeBytes(Content); random.close(); } catch (Exception exception) { //exception handling } 

如果您想要在特定行中添加一些文本,您可以先读取整个文件,将文本追加到任意位置,然后覆盖下面代码中的所有内容:

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

您可以使用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();