java追加寫入txt文件
阿新 • • 發佈:2017-12-08
output nal 代碼 public 整理 內容 fin ring str
整理了下網上的資料,數據追加寫入txt文件有三種方式,見下面代碼:
方法一:
1 public void method1() { 2 FileWriter fw = null; 3 try { 4 //如果文件存在,則追加內容;如果文件不存在,則創建文件 5 File f=new File("E:\\dd.txt"); 6 fw = new FileWriter(f, true); 7 } catch (IOException e) { 8 e.printStackTrace(); 9 } 10 PrintWriter pw = new PrintWriter(fw); 11 pw.println("追加內容");12 pw.flush(); 13 try { 14 fw.flush(); 15 pw.close(); 16 fw.close(); 17 } catch (IOException e) { 18 e.printStackTrace(); 19 } 20 }
方法二:
1 public static void method2(String file, String conent) { 2 BufferedWriter out = null; 3 try { 4 out = new BufferedWriter(new OutputStreamWriter( 5 new FileOutputStream(file, true))); 6 out.write(conent+"\r\n"); 7 } catch (Exception e) { 8 e.printStackTrace(); 9 } finally { 10 try { 11 out.close(); 12 } catch (IOException e) { 13 e.printStackTrace(); 14 } 15 } 16 }
方法三:
1 public static void method3(String fileName, String content) { 2 try { 3 // 打開一個隨機訪問文件流,按讀寫方式 4 RandomAccessFile randomFile = newRandomAccessFile(fileName, "rw"); 5 // 文件長度,字節數 6 long fileLength = randomFile.length(); 7 // 將寫文件指針移到文件尾。 8 randomFile.seek(fileLength); 9 randomFile.writeBytes(content+"\r\n"); 10 randomFile.close(); 11 } catch (IOException e) { 12 e.printStackTrace(); 13 } 14 } 15 }
java追加寫入txt文件