java GBK文件转UTF-8

    public String test(String inPath,String outPath) throws Exception {
        // 以GBK格式读取文件
        FileInputStream fis = new FileInputStream(inPath);
        InputStreamReader isr = new InputStreamReader(fis, "GBK");
        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 str2 = sb.toString();// 以UTF-8文件写入
        FileOutputStream fos = new FileOutputStream(outPath, false);
        OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
        osw.write(str2);
        osw.flush();
        osw.close();
        fos.close();
        br.close();
        isr.close();
        fis.close();
        return "文件生成成功";
    }

 

posted @ 2020-06-04 11:37  明知山有小脑斧  阅读(906)  评论(0编辑  收藏  举报