目录
- 简介
 - 文本文件的转码复制
 - 运行程序
 
简介
PrintWriter 与 PrintStream 相同。PrintStream 只能接字节流,而 PrintWriter 既能接字节流又能接字符流。
PrintStream 最终输出的总是 byte 数据,而 PrintWriter 则是扩展了 Writer 接口,它的 print()/println() 方法最终输出的是 char 数据。两者的使用方法几乎是一模一样的。
文本文件的转码复制
public class Main {
    public static void main(String[] args) {
        System.out.println("输入源文件");
        String s = new Scanner(System.in).nextLine();
        File from = new File(s);
        if (!from.isFile()) {
            System.out.println("请输入正确的文件路径");
            return;
        }
        System.out.println("输入目标文件");
        s = new Scanner(System.in).nextLine();
        File to = new File(s);
        if (to.isDirectory()) {
            System.out.println("请输入具体的文件路径,不是目录路径");
            return;
        }
        System.out.println("输入原文件字符编码");
        String fromCharset = new Scanner(System.in).nextLine();
        System.out.println("输入目标文件字符编码");
        String toCharset = new Scanner(System.in).nextLine();
        try {
            copy(from, to, fromCharset, toCharset);
            System.out.println("复制成功");
        } catch (Exception e) {
            System.out.println("复制失败");
        }
    }
    private static void copy(File from, File to, String fromCharset, String toCharset) throws Exception {
        // TODO Auto-generated method stub
        /**
         * 				BufferedReader
         * 			InputStreamReader,fromCharset
         *		FileInputStream
         *	from
         *
         *				PrintWriter
         *			OutputStreamWriter,toCharset
         *		FileOutputStream
         *	to
         *
         *	循环按行读写
         *
         * */
        BufferedReader in = new BufferedReader(
                new InputStreamReader(
                        new FileInputStream(from), fromCharset));
        PrintWriter out = new PrintWriter(
                new OutputStreamWriter(
                        new FileOutputStream(to), toCharset));
        String line;
        while ((line = in.readLine()) != null) {
            out.println(line);
        }
        in.close();
        out.close();
    }
}
运行程序

f7 内容为:

转为十六进制查看。原来编码为 UTF-8,英文单字节,中文3字节

f7copy 内容:

转为十六进制查看。现在编码为 GBK,英文单字节,中文双字节,增加了换行符

	声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
		
评论(0)