最近遇到這樣一個問題,我上傳文件沒有轉換字符集windows默認GBK,結果當我須要讀文件顯示時用UTF-8轉固然會出現亂碼,爲了解決這個問題,我就將上傳時文件一同也轉成UTF-8了這樣就不會亂碼了,上傳時轉換字符集方法以下:windows
String root = filePath;// 上傳路徑 File rootFile = new File(root); // 路徑不存在先建立路徑 if (!rootFile.exists()) { rootFile.mkdirs(); } // 獲取後綴type String suffix = domain.getSuffixName(); // 新文件名 String strNewName = domain.getScriptName().trim() + domain.getVersionName().trim() + "." + suffix; domain.setScriptUrl("/" + strNewName); File destFile; String destFilePath=root+"/"+strNewName; destFile = new File(root, strNewName); OutputStream outputStream; outputStream = new FileOutputStream(destFile); // file是上傳過來的文件,存放爲臨時tmp File file = domain.getFile(); String context = ""; InputStreamReader isr; isr = new InputStreamReader(new FileInputStream(file), "GBK"); BufferedReader br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { context += line + "\r\n"; System.out.println(line); } br.close(); byte[] content = context.getBytes(); context = new String(content, "UTF-8"); BufferedWriter writer; FileOutputStream fos = new FileOutputStream(destFilePath, true); System.out.println(root+"/"+strNewName); writer = new BufferedWriter(new OutputStreamWriter(fos, "UTF-8")); writer.append(context); writer.close();