温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

使用Java如何实现追加文件内容

发布时间:2020-11-17 16:02:49 来源:亿速云 阅读:146 作者:Leah 栏目:编程语言

这篇文章将为大家详细讲解有关使用Java如何实现追加文件内容,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

整理文档,搜刮出一个Java追加文件内容的三种方法的代码,稍微整理精简一下做下分享。

import Java.io.BufferedWriter; 
import java.io.File; 
import java.io.FileOutputStream; 
import java.io.FileWriter; 
import java.io.IOException; 
import java.io.OutputStreamWriter; 
import java.io.RandomAccessFile; 
 
/** 
 * 
 * @author malik 
 * @version 2011-3-10 下午10:49:41 
 */ 
public class AppendFile { 
   
  public static void method1(String file, String conent) {   
    BufferedWriter out = null;   
    try {   
      out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)));   
      out.write(conent);   
    } catch (Exception e) {   
      e.printStackTrace();   
    } finally {   
      try {   
        if(out != null){ 
          out.close();   
        } 
      } catch (IOException e) {   
        e.printStackTrace();   
      }   
    }   
  }   
  
  /**  
   * 追加文件:使用FileWriter  
   *  
   * @param fileName  
   * @param content  
   */  
  public static void method2(String fileName, String content) {  
    FileWriter writer = null; 
    try {   
      // 打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件   
      writer = new FileWriter(fileName, true);   
      writer.write(content);    
    } catch (IOException e) {   
      e.printStackTrace();   
    } finally {   
      try {   
        if(writer != null){ 
          writer.close();   
        } 
      } catch (IOException e) {   
        e.printStackTrace();   
      }   
    }  
  }   
  
  /**  
   * 追加文件:使用RandomAccessFile  
   *  
   * @param fileName 文件名  
   * @param content 追加的内容  
   */  
  public static void method3(String fileName, String content) {  
    RandomAccessFile randomFile = null; 
    try {   
      // 打开一个随机访问文件流,按读写方式   
      randomFile = new RandomAccessFile(fileName, "rw");   
      // 文件长度,字节数   
      long fileLength = randomFile.length();   
      // 将写文件指针移到文件尾。   
      randomFile.seek(fileLength);   
      randomFile.writeBytes(content);   
    } catch (IOException e) {   
      e.printStackTrace();   
    } finally{ 
      if(randomFile != null){ 
        try { 
          randomFile.close(); 
        } catch (IOException e) { 
          e.printStackTrace(); 
        } 
      } 
    } 
  }  
 
  public static void main(String[] args) { 
    try{ 
      File file = new File("d://text.txt"); 
      if(file.createNewFile()){ 
        System.out.println("Create file successed"); 
      } 
      method1("d://text.txt", "123"); 
      method2("d://text.txt", "123"); 
      method3("d://text.txt", "123"); 
    }catch(Exception e){ 
      System.out.println(e); 
    } 
  } 
} 

关于使用Java如何实现追加文件内容就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI