以当前默认file encoding读取文件然后以utf-8写入新文件
来源:互联网 发布:名片扫描软件哪个好 编辑:程序博客网 时间:2024/05/17 20:23
在简体中文Windows上, 默认启动的Java程序如果没有加上设置file encoding,那么默认生成的文件(写文件时没有指定编码的那种)是GBK编码的,这样的文件传输到其它非GBK编码的机器上会无法正常显示。 需要将其转换为utf-8格式的,这样就能在所有机器上以utf-8打开正常显示。
下面这段代码是如何将文件从当前默认的encoding读取后以utf-8写入
读取当前的file encodning (注意xxx.java文件是utf-8编码)
String fileEncoding = System.getProperty("file.encoding");
System.out.println("FileEncoding:" + fileEncoding);
try { String filePath= "d:\\dir1\\file1.txt"; File readfile = new File(filePath); if (readfile.isFile() && readfile.exists()) { //按照当前默认的file encoding独舞文件 InputStreamReader read = new InputStreamReader(new FileInputStream(readfile)); System.out.println("File Encoding:["+ read.getEncoding()); BufferedReader bufferedReader = new BufferedReader(read); String lineTxt = null; StringBuilder sb = new StringBuilder(); while ((lineTxt = bufferedReader.readLine()) != null) { sb.append(lineTxt).append("\n"); } read.close(); System.out.println("New:" + sb.toString()); File fileWriter = new File(filePath + "a"); if (fileWriter != null && fileWriter.exists()) { System.out.println("File["+fileWriter.getAbsolutePath() + "] already exists, Will not create it"); } else { System.out.println("File["+fileWriter.getAbsolutePath() + "] does not exists, create it"); //以utf-8写入文件 Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileWriter), "UTF-8")); try { out.write(sb.toString()); } finally { out.close(); } } } else { System.out.println("File:["+ readfile.getAbsolutePath() +"] does non exist"); } } catch (Exception e) { System.out.println("error"); e.printStackTrace(); }
可以在启动java程序时改变file enconding
set JAVA_OPTS=-Xmx512m -Dfile.encoding=UTF-8
或者java -jar xxxx -Dfile.encoding=UTF-8
1 0
- 以当前默认file encoding读取文件然后以utf-8写入新文件
- java读取写入utf-8编码文件
- Java以UTF-8编码读写文件
- python3 以utf-8编码写文件
- Java以UTF-8编码读写文件
- Java以UTF-8编码读写文件
- Java以UTF-8编码读写文件
- java实现以某种格式按行读取写入文件
- windows环境下新建.txt文件,使其默认以UTF-8编码
- Android 读取txt文件并以utf-8格式转换成字符串
- java以UTF-8编码写入文本文件
- 以当前时间命名文件
- QT读取xml文件,然后写入另外一个新的xml文件
- file 读取写入文件 HTML
- 文件FILE写入与读取
- 以固定编码读取文件
- 文件读写——以字符方式读取与写入文件
- lua实现以字符串内容写入文件,成功返回 true,失败返回 false读取文件内容
- oracle insert 转义&
- zcat命令查看压缩文件内容
- linux下 Wowza安装与ffmpeg测试
- 培训机构毕业的程序员被歧视的背后逻辑
- jQuery操作DOM对象
- 以当前默认file encoding读取文件然后以utf-8写入新文件
- CocoaPods安装
- tableView 的 cell 和 cell 的 imageView 的属性
- KindEditor 在线文档
- Ext简介(转)
- JQuery学习
- 浙江理工2015.12校赛-A
- iOS 最新版 CocoaPods 的安装流程
- Slope One