/**
* 字符流,读取文件并写入到新文件中
* 读取格式txt,xml...都可以
* @Author: www.itze.cn
* @param srcFile
* @param destFile
* @Date: 2020/9/27 9:12
* @Email: 814565718@qq.com
*/
public static void readCharsAndWrite(File srcFile, File destFile) {
if (!srcFile.exists()) {
throw new IllegalArgumentException("原文件:" + srcFile + "不存在!");
}
if (!srcFile.isFile()) {
throw new IllegalArgumentException(srcFile + "不是文件!");
}
try {
/**
* 参数说明,new InputStreamReader(args,args2)
* 第一个参数args是new FileInputStream(原文件路径)
* 第二个参数args2是以什么编码格式读取该文件,可以不写
* 默认读取为项目的编码格式,如果项编码格式为gbk则以该方式读取
* 建议设置要读取文件的编码格式,以防乱码!
*/
InputStreamReader reader = new InputStreamReader(new FileInputStream(srcFile), "UTF-8");
OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(destFile));
//读取原文件内容,读取字符流用char[],字节流用byte[]
char[] chars = new char[10 * 1024];
int b;
while ((b = reader.read(chars, 0, chars.length)) != -1) {
//写入到新文件中
writer.write(chars, 0, b);
writer.flush();
}
//关闭
reader.close();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}

使用方法

public static void main(String[] args) {
readCharsAndWrite(new File("D:\\context.xml"), new File("D:\\context2.xml"));
}