解决思路
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既为输出的内容,亲测不会乱码