ゞ沉默是金ゞ

          魚離不開水,但是沒有說不離開哪滴水.
          posts - 98,comments - 104,trackbacks - 0
          文件追加內(nèi)容實例
          package org.duke.java.util;

          import java.io.FileWriter;
          import java.io.IOException;
          import java.io.RandomAccessFile;

          public class AppendToFile {
              
          /**
               * A方法追加文件:使用RandomAccessFile
               
          */

              
          public static void appendMethodA(String fileName, String content) {
                  
          try {
                      
          // 打開一個隨機訪問文件流,按讀寫方式
                      RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
                      
          // 文件長度,字節(jié)數(shù)
                      long fileLength = randomFile.length();
                      
          //將寫文件指針移到文件尾。
                      randomFile.seek(fileLength);
                      randomFile.writeBytes(content);
                      randomFile.close();
                  }
           catch (IOException e) {
                      e.printStackTrace();
                  }

              }


              
          /**
               * B方法追加文件:使用FileWriter
               
          */

              
          public static void appendMethodB(String fileName, String content) {
                  
          try {
                      
          //打開一個寫文件器,構(gòu)造函數(shù)中的第二個參數(shù)true表示以追加形式寫文件
                      FileWriter writer = new FileWriter(fileName, true);
                      writer.write(content);
                      writer.close();
                  }
           catch (IOException e) {
                      e.printStackTrace();
                  }

              }


              
          public static void main(String[] args) {
                  String fileName 
          = "C:/Shawn/test.txt";
                  String content 
          = "new append!";
                  
          //按方法A追加文件
                  AppendToFile.appendMethodA(fileName, content);
                  AppendToFile.appendMethodA(fileName, 
          "append end. \n");
                  
          //顯示文件內(nèi)容
                  ReadFromFile.readFileByLines(fileName);
                  
          //按方法B追加文件
                  AppendToFile.appendMethodB(fileName, content);
                  AppendToFile.appendMethodB(fileName, 
          "append end. \n");
                  
          //顯示文件內(nèi)容
                  ReadFromFile.readFileByLines(fileName);
              }

          }


          posted on 2012-07-03 19:10 ゞ沉默是金ゞ 閱讀(777) 評論(0)  編輯  收藏 所屬分類: Java SE
          主站蜘蛛池模板: 南郑县| 城口县| 康乐县| 晋州市| 安新县| 宜城市| 连云港市| 德令哈市| 桦甸市| 黄骅市| 饶河县| 衡东县| 利津县| 全州县| 惠安县| 铅山县| 鄂托克前旗| 揭西县| 威海市| 塔河县| 鸡东县| 麦盖提县| 宣武区| 恩平市| 德安县| 汉中市| 武穴市| 青铜峡市| 望江县| 延川县| 响水县| 安化县| 磐石市| 鹤壁市| 龙陵县| 屯门区| 大洼县| 建平县| 顺义区| 新巴尔虎左旗| 禹州市|