这篇文章主要介绍了Java中PrintWriter使用方法介绍,文章围绕主题展开PrintWriter使用方法的详细介绍,具有一定的参考价值,感兴趣的小伙伴可以参考一下
简介
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,英文单字节,中文双字节,增加了换行符
到此这篇关于Java中PrintWriter使用方法介绍的文章就介绍到这了,更多相关Java PrintWriter内容请搜索编程学习网以前的文章希望大家以后多多支持编程学习网!
沃梦达教程
本文标题为:Java中PrintWriter使用方法介绍
猜你喜欢
- Spring Security权限想要细化到按钮实现示例 2023-03-07
- Springboot整合minio实现文件服务的教程详解 2022-12-03
- ExecutorService Callable Future多线程返回结果原理解析 2023-06-01
- SpringBoot使用thymeleaf实现一个前端表格方法详解 2023-06-06
- 深入了解Spring的事务传播机制 2023-06-02
- Java实现顺序表的操作详解 2023-05-19
- 基于Java Agent的premain方式实现方法耗时监控问题 2023-06-17
- JSP页面间传值问题实例简析 2023-08-03
- JSP 制作验证码的实例详解 2023-07-30
- Java中的日期时间处理及格式化处理 2023-04-18