上传txt文件乱码问题

1.问题

今天同事反映有上传的txt文件存在乱码问题,然后新建一个txt文件发现并没有这个问题,最后用同事发给我的txt文件测试了一下 ,发现果然乱码了。百度了一下,是txt文件的编码格式引起的。乱码展示

2.解决方案

方法1:

修改txt文件的编码格式,重新上传。并修改新建txt文件的默认编码格式。设置方式【引用】
按照网上设置新建txt文件编码格式的方法,发现太过复杂,如果客户的电脑都设置,太浪费时间。

方法2

采用代码解决,统一转换为我们需要的编码格式。

代码部分

获取当前txt文件的编码格式

/** 
 * 判断文件的编码格式 
 * @param InputStream :is
 * @return 文件编码格式 
 * @throws Exception 
 */  
public static String getCharset(InputStream is) throws IOException {
        BufferedInputStream bin = new BufferedInputStream(is);
        int p = (bin.read() << 8) + bin.read();//读取文件头前16位  
        String code = null;
        switch (p) {
            case 0xefbb:
                code = "UTF-8";
                break;
            case 0xfffe:
                code = "Unicode";
                break;
            case 0xfeff:
                code = "UTF-16";
                break;
            default:
                code = "GB2312";
        }
        return code;
    }

统一转为utf-8编码的文件

/**
 * 解决txt乱码问题
 * @param is
 * @param targetFile 转换完成后的新文件
 * @param code 需要转换的文件的编码格式
 * @return File 
 * @throws IOException
 */
    public static File FileTurnUTF8(InputStream is, File targetFile, String code) throws IOException {
        if (!targetFile.exists()) {
            targetFile.createNewFile();
        }
        BufferedReader br = null;
        BufferedWriter bw = null;
        br = new BufferedReader(new InputStreamReader(is, code));
        bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(targetFile), "UTF-8"));
        int i = 0;
        String str = "";
        while ((str = br.readLine()) != null) {
            byte[] bytes = str.getBytes("UTF-8");
            str = new String(bytes, 0, bytes.length);
            bw.write(str + "\r\n");
        }

        br.close();
        bw.close();
        return targetFile;
    }

因为前端传过来的是MultipartFile类型的,转换完成后还需要把File转换成MultipartFile。

/**
 * File 转 MultipartFile
 * 
 * @param file
 * @throws Exception
 */
    public MultipartFile fileToMultipartFile(File file) throws Exception {

        FileInputStream fileInput = new FileInputStream(file);
        MultipartFile toMultipartFile = new MockMultipartFile("file", file.getName(), "text/plain",
                        IOUtils.toByteArray(fileInput));
        toMultipartFile.getInputStream();
        return toMultipartFile;

    }

完成效果

成功展示

发布了26 篇原创文章 · 获赞 6 · 访问量 2958

猜你喜欢

转载自blog.csdn.net/weixin_45676630/article/details/101532633
今日推荐