码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-06-25 17:07:31      阅读:246      评论:0      收藏:0      [点我收藏+]

标签:exce   pac   main   line   txt   java   port   ack   source   

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格式读写及追加写文件示例

标签:exce   pac   main   line   txt   java   port   ack   source   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!