1. Problem
Today, colleagues reflect the existence of the garbage problem has uploaded the txt file and then create a new txt file and found no problem, and finally with a colleague sent me a txt file tested it and found it really garbled. Baidu a little, it is caused by coding format txt file.
2. Solution
method 1:
Modify the encoding format txt file, re-upload. Txt file and modify the new default encoding format. [Quote] arrangement
in accordance with the new method txt file encoding format settings online, found too complicated, if a customer's computers are set up, a waste of time.
Method 2
The use of the code to solve, we need a unified converted into a coded format.
Code section
Gets the current encoding format txt file
/**
* 判断文件的编码格式
* @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;
}
Unified into utf-8 encoded files
/**
* 解决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;
}
Since the distal end is passed over MultipartFile type, after the conversion is completed also need to be converted into MultipartFile File.
/**
* 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;
}