国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

Java追加文件內容的三種方法實例代碼

2019-11-26 12:32:06
字體:
來源:轉載
供稿:網友

整理文檔,搜刮出一個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);     }   } } 

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 屏东市| 马山县| 商都县| 望奎县| 云浮市| 根河市| 德庆县| 兖州市| 弋阳县| 双桥区| 吉木萨尔县| 左云县| 麟游县| 中西区| 察哈| 比如县| 扶绥县| 高要市| 沅陵县| 商都县| 襄汾县| 紫阳县| 水城县| 清原| 东丰县| 黎平县| 商河县| 南靖县| 都江堰市| 镇沅| 广州市| 安乡县| 岑溪市| 抚州市| 博爱县| 盈江县| 鄂伦春自治旗| 镇赉县| 永春县| 宁明县| 德令哈市|