CSV 文件 上傳 亂碼
項目有上傳csv文件的功能的,一開始upload中文的文件是沒有亂碼出現的,但是某一版本開始就出現亂碼了。
調試了很多方法,發現上傳的格式是沒有錯的,請求的編碼和接受的編碼是一致的,但還是出現亂碼。
后來檢查代碼發現是讀取csv文件的時候出現亂碼,原來的寫法是沒有規定使用哪種編碼來讀取csv文件,所以讀取出來的代碼亂碼了,更換了讀取csv文件的寫法,並使用UTF-8編碼格式來讀取后,亂碼的文件就解決了!
原來的寫法:
public void test42() throws IOException {
String fileName = "D:\\Logs\\MMS\\upload_9e6610d5_e516_4902_81ed_374763055092_00000000.tmp";
java.io.File file = new java.io.File(fileName);
BufferedReader reader = null;
try {
System.out.println("以行為單位讀取文件內容,一次讀一整行:");
reader = new BufferedReader(new FileReader(file));
String tempString = null;
int line = 1;
// 一次讀入一行,直到讀入null為文件結束
while ((tempString = reader.readLine()) != null) {
// 顯示行號
System.out.println("line " + line + ": " + tempString);
line++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
}
更改后的寫法:
public void test42() throws IOException {
String fileName = "D:\\Logs\\MMS\\upload_9e6610d5_e516_4902_81ed_374763055092_00000000.tmp";
java.io.File file = new java.io.File(fileName);
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
BufferedReader br = new BufferedReader(isr);
try {
System.out.println("以行為單位讀取文件內容,一次讀一整行:");
String tempString = null;
int line = 1;
// 一次讀入一行,直到讀入null為文件結束
while ((tempString = br.readLine()) != null) {
// 顯示行號
System.out.println("line " + line + ": " + tempString);
line++;
}
br.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e1) {
}
}
}
}
亂碼的問題很多時候都是出現在讀取的時候沒有規定編碼或者讀與取使用了不一樣的編碼,所以出現亂碼可以先查看讀取到編碼是不是使用了不一樣的編碼。
然后發現每次修改完csv文件后,都會默認鍵csv文件保存為 ANSI 編碼格式,但是我們的項目是用統一用UTF-8的,所以upload就出現亂碼了。
用notepad++吧csv文件的保存格式修改為UTF-8后,就沒有出現亂碼了