问题描述
java程序通过new java.io.FileReader(file)读取文件,文件内容有中文,最终读取到的中文产生乱码。
阅读代码
package java.io;
public class FileReader extends InputStreamReader {
public FileReader(File file) throws FileNotFoundException {
super(new FileInputStream(file));
}
}
package java.io;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import sun.nio.cs.StreamDecoder;
public class InputStreamReader extends Reader {
private final StreamDecoder sd;
public InputStreamReader(InputStream in) {
super(in);
try {
sd = StreamDecoder.forInputStreamReader(in, this, (String)null); // ## check lock object
} catch (UnsupportedEncodingException e) {
// The default encoding should always be available
throw new Error(e);
}
}
public InputStreamReader(InputStream in, String charsetName)
throws UnsupportedEncodingException
{
super(in);
if (charsetName == null)
throw new NullPointerException("charsetName");
sd = StreamDecoder.forInputStreamReader(in, this, charsetName);
}
public InputStreamReader(InputStream in, Charset cs) {
super(in);
if (cs == null)
throw new NullPointerException("charset");
sd = StreamDecoder.forInputStreamReader(in, this, cs);
}
}
package sun.nio.cs;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CoderResult;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.IllegalCharsetNameException;
public class StreamDecoder extends Reader {
private static final int MIN_BYTE_BUFFER_SIZE = 32;
private static final int DEFAULT_BYTE_BUFFER_SIZE = 8192;
private volatile boolean isOpen;
private boolean haveLeftoverChar;
private char leftoverChar;
private static volatile boolean channelsAvailable = true;
private Charset cs;
private CharsetDecoder decoder;
private ByteBuffer bb;
private InputStream in;
private ReadableByteChannel ch;
public static StreamDecoder forInputStreamReader(InputStream var0, Object var1, String var2) throws UnsupportedEncodingException {
String var3 = var2;
if (var2 == null) {
var3 = Charset.defaultCharset().name();
}
try {
if (Charset.isSupported(var3)) {
return new StreamDecoder(var0, var1, Charset.forName(var3));
}
} catch (IllegalCharsetNameException var5) {
}
throw new UnsupportedEncodingException(var3);
}
}
package java.nio.charset;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.spi.CharsetProvider;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.ServiceLoader;
import java.util.ServiceConfigurationError;
import java.util.SortedMap;
import java.util.TreeMap;
import sun.misc.ASCIICaseInsensitiveComparator;
import sun.nio.cs.StandardCharsets;
import sun.nio.cs.ThreadLocalCoders;
import sun.security.action.GetPropertyAction;
public abstract class Charset
implements Comparable<Charset>
{
private static volatile Charset defaultCharset;
/**
* Returns the default charset of this Java virtual machine.
*
* <p> The default charset is determined during virtual-machine startup and
* typically depends upon the locale and charset of the underlying
* operating system.
*
* @return A charset object for the default charset
*
* @since 1.5
*/
public static Charset defaultCharset() {
if (defaultCharset == null) {
synchronized (Charset.class) {
String csn = AccessController.doPrivileged(
new GetPropertyAction("file.encoding"));
Charset cs = lookup(csn);
if (cs != null)
defaultCharset = cs;
else
defaultCharset = forName("UTF-8");
}
}
return defaultCharset;
}
public final String name() {
return name;
}
}
从方法注释可以看出,默认字符集是在虚拟机启动时确定的,并且通常取决于底层操作系统的区域和字符集。
package sun.security.action;
import java.security.AccessController;
import java.security.PrivilegedAction;
public class GetPropertyAction implements PrivilegedAction<String> {
private String theProp;
private String defaultVal;
public GetPropertyAction(String var1) {
this.theProp = var1;
}
public GetPropertyAction(String var1, String var2) {
this.theProp = var1;
this.defaultVal = var2;
}
public String run() {
String var1 = System.getProperty(this.theProp);
return var1 == null ? this.defaultVal : var1;
}
public static String privilegedGetProperty(String var0) {
return System.getSecurityManager() == null ? System.getProperty(var0) : (String)AccessController.doPrivileged(new GetPropertyAction(var0));
}
public static String privilegedGetProperty(String var0, String var1) {
return System.getSecurityManager() == null ? System.getProperty(var0, var1) : (String)AccessController.doPrivileged(new GetPropertyAction(var0, var1));
}
}
可以看出通过System.getProperty(this.theProp)获取系统属性。
如果你需要更改JVM的默认字符集,可以通过在启动JVM时指定-Dfile.encoding属性来实现。例如,你可以使用-Dfile.encoding=UTF-8来将默认字符集设置为UTF-8。
需要注意的是,操作系统字符集的设置也有相应的优先级。通常,LC_ALL设置具有最高的优先级,它可以强制设置字符集。如果没有设置LC_ALL,那么会考虑LC_设置,最后是LANG设置。LANG是LC_的默认值,而LC_ALL比LC_的优先级别高,设置完LC_ALL之后,会强制重置LC_各个值,如果不将LC_ALL重新设置为空,则再无法设置LC_*的单个值 。
排查
- java程序没有设置file.encoding
- Linux中使用locale查看系统编码发现使用的是GBK,到此乱码原因找到。
解决方法
- java程序启动时指定-Dfile.encoding=UTF-8。
示例:java -Dfile.encoding=UTF-8 -jar demo.jar - 修改操作系统默认字符集编码。
/etc/profile是系统级的配置文件,它应用于所有用户。
~/.bash_profile是用户级的配置文件,它只适用于当前登录用户。
系统会首先加载/etc/profile,然后加载~/.bash_profile。
这意味着用户级的配置文件会覆盖系统级的配置文件,因为后者的配置会在前者之后加载。
1、sudo vim ~/.bash_profile
2、export LC_ALL=en_US.UTF-8
3、source ~/.bash_profile
4、重启java程序