首页 > 编程语言 > 详细

Java以UTF-8格式读写及追加写文件示例

时间:2018-06-25 16:12:09      阅读:289      评论:0      收藏:0      [点我收藏+]
package test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class FileHelper {
    
    public static void readFile(File file) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
        String line = null;   
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }  
    }
    
    public static void writeFile(File file, String content) throws IOException {
        FileOutputStream fos = new FileOutputStream(file);
        OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
        osw.write(content);
        osw.flush();
    }
    
    public static void appendFile(File file, String content) throws IOException {
        OutputStreamWriter out = new OutputStreamWriter(
                new FileOutputStream(file, true), // true to append
                "UTF-8"
                );
        out.write(content);
        out.close();
    }
    
    // main for test
    public static void main(String[] args) throws IOException {
        File file = new File("D:\\test.txt");
        writeFile(file, "");
        appendFile(file, "你好");
        appendFile(file, "!!!");
        readFile(file);
    }
}

Java以UTF-8格式读写及追加写文件示例

原文:https://www.cnblogs.com/zifeiy/p/9224569.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!