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

java io 读取写文件

时间:2017-11-02 15:58:17      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:commons   buffered   字符   file   ted   ring   util   line   write   

java 读取txt文件,汉字乱码,原因是因为文件的编码格式和程序编码采用了不同的编码格式。通常,假如自己不修改的话,windows自身采用的编码格式是gbk(而gbk和gb2312基本上是一样的编码方式),程序中一般采用utf-8,所以读取文件的时候最好指定编码方式

  方式1:以字节流读写

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;

import org.apache.commons.lang3.StringUtils;

public class FileReadWriteDemo2 {

    public static void main(String[] args) throws IOException {

        BufferedReader read = new BufferedReader(new InputStreamReader(new FileInputStream("f:/test.txt"),"gbk"));
        Writer out = new OutputStreamWriter(new FileOutputStream("f:/testNew.txt"),"gbk");
        BufferedWriter writer =new BufferedWriter(out);
        String fileContent ="";
        String line = "";
        while ((line = read.readLine()) != null) {
            //删除空格
            if (StringUtils.isNotBlank(line)) {
                //System.out.println(line);
                fileContent +=line+"\r\n";
                writer.write(line);
                writer.write("\r\n");
            }
        }
        read.close();
        writer.close();
        System.out.println(fileContent);
    }
}

 方式2:以字符流读写

public class FileReadWriteDemo {

    public static void main(String[] args) throws IOException {
        BufferedReader read = new BufferedReader(new FileReader("f:\\test.txt"));

        BufferedWriter writer = new BufferedWriter(new FileWriter("f:/testNew.txt"));
        
        String line = "";
        while ((line = read.readLine()) != null) {
        
            if (StringUtils.isNotBlank(line)) {
                System.out.println(line);
                writer.write(line);
                writer.write("\n ");
            }
        }
        read.close();
        writer.close();
    }
}

 

java io 读取写文件

标签:commons   buffered   字符   file   ted   ring   util   line   write   

原文地址:http://www.cnblogs.com/newlangwen/p/7772081.html

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