Java PrintWriter
奔跑吧鸡翅 人气:0简介
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,英文单字节,中文双字节,增加了换行符
加载全部内容