java上传txt文件读取内容是乱码问题解决

解决思路

1,识别用户上传的文件的编码格式
2,根据用户上传的编码格式进行获取用户的txt文件内容信息

上干货

加入依赖
		<!--此依赖用于获取用户上传的txt文件中的文字信息-->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.11.0</version>
        </dependency>
		<!--此依赖用于获取用户上传文件的编码格式-->
        <dependency>
            <groupId>com.googlecode.juniversalchardet</groupId>
            <artifactId>juniversalchardet</artifactId>
            <version>1.0.3</version>
        </dependency>

代码实现

            String encoding ="";

            try (InputStream inputStream = file.getInputStream()) {
                byte[] buffer = new byte[4096];
                UniversalDetector detector = new UniversalDetector(null);

                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) > 0 && !detector.isDone()) {
                    detector.handleData(buffer, 0, bytesRead);
                }

                detector.dataEnd();

                encoding = detector.getDetectedCharset();
                detector.reset();
            } catch (IOException e) {
                e.printStackTrace();
                return AjaxResult.error("上传txt文件异常,请联系管理员");
            }

这里输出encoding既为匹配到的编码格式

根据文件的编码格式进行转化 转化为需要的UTF-8格式

String content = null;
            String utf8Content ="";
            try {
                content = IOUtils.toString(file.getInputStream(), Charset.forName(encoding));

                CharsetDetector detector = new CharsetDetector();
                detector.setText(content.getBytes());
                CharsetMatch match = detector.detect();
                String detectedCharset = match.getName();

                utf8Content = new String(content.getBytes(detectedCharset), StandardCharsets.UTF_8);
            } catch (IOException e) {
                e.printStackTrace();
            }

这里的content既为输出的内容,亲测不会乱码

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值