import java.io.*; /** * @ClassName CharSetTransferExample * @projectName: object1 * @author: Zhangmingda * @description: XXX * date: 2021/4/18. */ public class CharSetTransferExample { public static void main(String[] args) { String textPath = "输入输出文件读写/src/test/output/windows-create-剑门关.txt"; String tmpLine; try(BufferedReader bufferedReader = new BufferedReader(new FileReader(textPath))) { while ((tmpLine = bufferedReader.readLine()) != null){ System.out.println(tmpLine); } }catch (FileNotFoundException e){ e.printStackTrace(); }catch (IOException e){ e.printStackTrace(); } } }
输出结果:
解决方案:通过转换流 指定字符编码 转换字节流如下↓↓↓
语法:
import java.io.*; /** * @ClassName CharSetTransferExample * @projectName: object1 * @author: Zhangmingda * @description: XXX * date: 2021/4/18. */ public class CharSetTransferExample { public static void main(String[] args) { String textPath = "输入输出文件读写/src/test/output/windows-create-剑门关.txt"; String tmpLine; // try(BufferedReader bufferedReader = new BufferedReader(new FileReader(textPath))) { // 打开GBK编码文本,输出乱码 try(BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(textPath),"GBK"))) { while ((tmpLine = bufferedReader.readLine()) != null){ System.out.println(tmpLine); /** * 剑门关-V哥 * 北望剑阁一线天, * 遥想翼德战关前。 * 纵使王朝风云变, * 雄关笑傲数千年。 */ } }catch (FileNotFoundException e){ e.printStackTrace(); }catch (IOException e){ e.printStackTrace(); } } }
import java.io.*; /** * @ClassName WriteTextOutputStreamCharSetTransferExample * @projectName: object1 * @author: Zhangmingda * @description: XXX * date: 2021/4/18. */ public class WriteTextOutputStreamCharSetTransferExample { public static void main(String[] args) { String dstTextPath = "输入输出文件读写/src/test/output/idea-write-gbkString.txt"; try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(dstTextPath),"GBK"))){ bw.write("我好爱你,爱爱爱啊!"); bw.flush(); }catch (UnsupportedEncodingException e){ e.printStackTrace(); }catch (FileNotFoundException e){ e.printStackTrace(); }catch (IOException e) { e.printStackTrace(); } } }
写入GBK编码字符成功,IDEA打提示当前默认使用UTF-8打开,建议用GBK编码reload
原文:https://www.cnblogs.com/zhangmingda/p/14673821.html