国产探花免费观看_亚洲丰满少妇自慰呻吟_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);     }   } } 

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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 商南县| 万载县| 永平县| 建阳市| 会宁县| 库伦旗| 吉首市| 施甸县| 丁青县| 长垣县| 仲巴县| 宁国市| 大埔县| 新营市| 台州市| 宣汉县| 黄大仙区| 蒙阴县| 高唐县| 南乐县| 沛县| 怀来县| 通州市| 泊头市| 安康市| 石首市| 新巴尔虎左旗| 丰镇市| 益阳市| 九江县| 邯郸市| 博爱县| 永顺县| 福贡县| 肥东县| 唐河县| 乌审旗| 凌云县| 富蕴县| 海安县| 无极县|