java读取本地文件中文乱码问题

客户的服务器美国的服务器,没有中文utf-8字符集,java读取的时候中文乱码。

java读取文件的方式如下:

FileUtils.readFileToString(file,fileEncode);

 

解决方法:

1.安装中文字符集。

2.使用第三方判断文件字符集的jar包。资源如下:juniversalchardet-1.0.3.jar .代码如下:

  public static String getCharset(String path) {
        File file = new File(path);
        UniversalDetector detector = new UniversalDetector(null);
        try(InputStream is = new FileInputStream(file)) {
            byte[] bytes = new byte[1024];
            int nread;
            if ((nread = is.read(bytes)) > 0 && !detector.isDone()) {
                detector.handleData(bytes, 0, nread);
            }
        } catch (Exception localException) {
            System.out.println("detected code:"+localException);
        }
        detector.dataEnd();
        String encode = detector.getDetectedCharset();
        /** default UTF-8 */
        if ((encode == null || encode.length() == 0)) {
            encode = "UTF-8";
        }
        detector.reset();
        return encode;
    }

你可能感兴趣的:(java,Java,字符集,windows)