java更改⽂件字符集编码
/* *
* @Author adolph
* @Description 更改⽂件的字符集编码 * @Date 9:19 2020/5/26 * @Param [file,contentType] * @return java.io.File **/
public File changedContentType(File file,String contentType) throws IOException{ //获取已获取的字符输⼊流
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis); BufferedReader br = new BufferedReader(isr); String str = null;
// 创建StringBuffer字符串缓存区 StringBuffer sb = new StringBuffer(); // 通过readLine()⽅法遍历读取⽂件 while ((str = br.readLine()) != null) {
// 使⽤readLine()⽅法⽆法进⾏换⾏,需要⼿动在原本输出的字符串后⾯加\"\\n\"或\"\\r\" str += \"\\n\"; sb.append(str); }
String fileSource = sb.toString();
// 以GBK格式写⼊⽂件,file.getAbsolutePath()即该⽂件的绝对路径,false代表不追加直接覆盖,true代表追加⽂件 FileOutputStream fos = new FileOutputStream(file.getAbsolutePath(), false); OutputStreamWriter osw = new OutputStreamWriter(fos, contentType); try{
osw.write(fileSource); return file;
}catch(Exception e){ e.printStackTrace(); return null; }finally {
osw.flush(); osw.close(); fos.close(); br.close(); isr.close(); fis.close(); } }