1. 程式人生 > >Java寫入txt檔案內容

Java寫入txt檔案內容

Java寫入資料進txt檔案,需求:多條資料追加進檔案,且需要處理中文編碼問題。

以下程式碼只能處理向檔案新增資料的功能,但是會覆蓋掉之前的資料

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class Write {
    public static void main(String[] args) throws IOException {
        String word = "hahahahhahahahhah";
        FileOutputStream fileOutputStream = null
; File file = new File("F:\\test\\test.txt"); if(!file.exists()){ file.createNewFile(); } fileOutputStream = new FileOutputStream(file); fileOutputStream.write(word.getBytes("gbk")); fileOutputStream.flush(); fileOutputStream.close(); } }

正確例項

public class Test{
    public static void main(String[] args) throws IOException {
        String path = "F:\\test\\test.txt";
        String word = "試試";
        BufferedWriter out = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(path,true)));
        out
.write(word+"\r\n"); out.close(); } }