栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java追加文件内容的三种方法实例代码

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/146659.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号