java.io.FileWriter class doesn’t use UTF-8 by default
2016-02-20 20:32
435 查看
Oddly enough the java.io.FileWriter class doesn’t use UTF-8 by default. I’m not exactly sure what the default encoding is (possibly ISO-8859-1 or US-ASCII?) but it doesn’t seem to be UTF-8, which is odd given that java strings are supposed to be unicode. This
causes a problem if you want to have non-ascii characters and you don’t realise what’s happening. This was a bug in SQLEditor and somebody accidentally typed an umlaut into one of the fields and the file wouldn’t reload. (Which was annoying).
The correct thing to do seems to be to use the following:
Which ensures that you are using UTF-8.
I suppose that the motivation for this is that it means that simple use of FileWriter is compatible with applications that are not unicode aware and don’t support UTF-8. It probably makes sense at some level, but it just goes to show that you can’t assume anything.
causes a problem if you want to have non-ascii characters and you don’t realise what’s happening. This was a bug in SQLEditor and somebody accidentally typed an umlaut into one of the fields and the file wouldn’t reload. (Which was annoying).
The correct thing to do seems to be to use the following:
OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(path),"UTF-8");
Which ensures that you are using UTF-8.
I suppose that the motivation for this is that it means that simple use of FileWriter is compatible with applications that are not unicode aware and don’t support UTF-8. It probably makes sense at some level, but it just goes to show that you can’t assume anything.
相关文章推荐
- java自己主动生成验证码
- java设计模式——观察者模式
- Java 异常
- Struts2 HelloWorld
- java继承,抽象类
- Java 集合系列05之 LinkedList详细介绍(源码解析)和使用示例
- Java 容器
- Spring MVC 中的 forward 和 redirect 的简单理解
- Struts2之result的配置
- (新手向)spring-boot Gradle installation
- Struts2之Action的基本配置
- Struts2之访问ServletAPI
- Struts2之入门
- LEEDCODE 13 Roman to Integer (JAVA题解)
- EGit with eclipse to clone project from GitHub(Step by step)
- Java-Map测试-学生选课
- Java 排名第一的4个理由
- Java-Set测试-学生选课
- Java数据类型
- Java学习笔记2016.2.20 包装类、数组