上傳檔案轉換編碼(using Java)

網頁服務滿常有上傳檔案這個基本功能,偶爾會遇到編碼的問題,這裡分享一下上傳檔案後轉換成utf-8的方法。

JeffChang
3 min readJul 10, 2020

主程式邏輯中,先判斷檔案的編碼是什麼,再依照編碼去判斷是否要另外用指定編碼產生新檔案。

String fileEncode = getCharsetByBOM(file);
logger.info("The encoding of upload file : " + fileEncode);
/* Change the encoding if the that was not UTF-8 */
if (!fileEncode.equals("UTF-8")) {
saveAsNewFile(file, filePath, fileEncode);
logger.info(String.format("Encoding of upload file: %s -> UTF-8", fileEncode));
} else {
file.renameTo(new File(filePath));
}

判斷編碼的方法如下

/**
* Distinguish the encoding of the input file using BOM.
* @param file
* @return
* @throws Exception
*/
private static String getCharsetByBOM(File file) throws Exception {
BufferedInputStream bin = new BufferedInputStream(new FileInputStream(file));
int p = (bin.read() << 8) + bin.read();
String encode = null;
switch (p) {
case 0xefbb:
encode = "UTF-8";
break;
case 0xfffe:
encode = "Unicode";
break;
case 0xfeff:
encode = "UTF-16BE";
break;
default:
encode = "BIG5";
}
return encode;
}

若指定編碼不是utf-8,則另外產生指定編碼的新檔案。

/**
* Save the file to certain directory in UTF-8 encoding.
* @param file - The uploaded file
* @param filePath - Output file path
* @param currentEncode - The encoding type of uploaded file
* @throws Exception
*/
public static void saveAsNewFile(File file, String filePath, String currentEncode) throws Exception {
InputStream fin = new FileInputStream(file);
FileOutputStream fout = new FileOutputStream(new File(filePath));
byte[] c = new byte[(int) file.length()];
while (fin.available() > 0) {
fin.read(c);
fout.write(new String(c, currentEncode).getBytes("utf-8"));
}
fin.close();
fout.close();
}

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

JeffChang
JeffChang

Written by JeffChang

Java Backend Engineer In DDIM.

No responses yet

Write a response