Java追加文件
1 import java.io.BufferedWriter; 2 import java.io.File; 3 import java.io.FileOutputStream; 4 import java.io.FileWriter; 5 import java.io.IOException; 6 import java.io.OutputStreamWriter; 7 import java.io.RandomAccessFile; 8 9 /** 10 * 11 * @author FJL 12 * @version 2013-10-1 13 */ 14 public class AppendFile { 15 16 public static void method1(String file, String conent) { 17 BufferedWriter out = null; 18 try { 19 out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true))); 20 out.write(conent); 21 } catch (Exception e) { 22 e.printStackTrace(); 23 } finally { 24 try { 25 if(out != null){ 26 out.close(); 27 } 28 } catch (IOException e) { 29 e.printStackTrace(); 30 } 31 } 32 } 33 34 /** 35 * 追加文件:使用FileWriter 36 * 37 * @param fileName 38 * @param content 39 */ 40 public static void method2(String fileName, String content) { 41 FileWriter writer = null; 42 try { 43 // 打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件 44 writer = new FileWriter(fileName, true); 45 writer.write(content); 46 } catch (IOException e) { 47 e.printStackTrace(); 48 } finally { 49 try { 50 if(writer != null){ 51 writer.close(); 52 } 53 } catch (IOException e) { 54 e.printStackTrace(); 55 } 56 } 57 } 58 59 /** 60 * 追加文件:使用RandomAccessFile 61 * 62 * @param fileName 文件名 63 * @param content 追加的内容 64 */ 65 public static void method3(String fileName, String content) { 66 RandomAccessFile randomFile = null; 67 try { 68 // 打开一个随机访问文件流,按读写方式 69 randomFile = new RandomAccessFile(fileName, "rw"); 70 // 文件长度,字节数 71 long fileLength = randomFile.length(); 72 // 将写文件指针移到文件尾。 73 randomFile.seek(fileLength); 74 randomFile.writeBytes(content); 75 } catch (IOException e) { 76 e.printStackTrace(); 77 } finally{ 78 if(randomFile != null){ 79 try { 80 randomFile.close(); 81 } catch (IOException e) { 82 e.printStackTrace(); 83 } 84 } 85 } 86 } 87 88 public static void main(String[] args) { 89 try{ 90 File file = new File("d://text.txt"); 91 if(file.createNewFile()){ 92 System.out.println("Create file successed"); 93 } 94 method1("d://text.txt", "123"); 95 method2("d://text.txt", "123"); 96 method3("d://text.txt", "123"); 97 }catch(Exception e){ 98 System.out.println(e); 99 } 100 } 101 }