java io 读取写文件
Posted newlangwen
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java io 读取写文件相关的知识,希望对你有一定的参考价值。
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 读取写文件的主要内容,如果未能解决你的问题,请参考以下文章
solr分布式索引实战分片配置读取:工具类configUtil.java,读取配置代码片段,配置实例