Summary of two ways that java adds data to the tail of file

  • 2020-10-31 21:45:46
  • OfStack

java summarizes two ways of adding data to the tail of file

Problem description:

Appends content to the end of the file

Method 1: Take advantage of the RandomAccessFile class

1. Set randomAccessFile mode to rw
Move randomAccessFile (seek) to the end of the file
3 Append data
4 close the flow

Method 2: Take advantage of the FileWriter class

1. Set the second parameter of FileWriter constructor to true, which means append to the tail
2 Append data
3. Close the flow

Implementation code:


package cn.com; 
import java.io.FileWriter; 
import java.io.RandomAccessFile; 
public class FileTest { 
 public static void main(String[] args) { 
  FileTest fileTest = new FileTest(); 
  fileTest.addContentFirst("F:\\temp.txt", "test1"); 
  fileTest.addContentSecond("F:\\temp.txt", "test2"); 
 } 
 
 public void addContentFirst(String filePath, String newContent) { 
  try { 
   RandomAccessFile randomAccessFile=new RandomAccessFile(filePath, "rw"); 
   long fileLength=randomAccessFile.length(); 
   randomAccessFile.seek(fileLength); 
   randomAccessFile.write(newContent.getBytes("UTF-8")); 
   randomAccessFile.close(); 
  } catch (Exception e) { 
  } 
 } 
 
 public void addContentSecond(String filePath, String newContent) { 
  try { 
   FileWriter fileWriter=new FileWriter(filePath, true); 
   fileWriter.write(newContent); 
   fileWriter.close(); 
  } catch (Exception e) { 
  } 
 } 
} 

If you have any questions, please leave a message or go to this site community exchange discussion, thank you for reading, I hope to help you, thank you for your support to this site!


Related articles: