java 输入流和输出流指定字符集,防止中文乱码

  • Post author:
  • Post category:java


输出流:将内存中的数据写入到磁盘文件中,防止中文乱码,需要指定writer的字符集

BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(“D:\\test.txt”,true,”UTF-8″)));

writer.write(“我是中文”);

输入流:将磁盘文件读入内存,防止中文乱码,需指定输入流reader的字符集

BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(“D:\\test.txt”),”UTF-8″))

String s = null;

StringBuilder sb = new StringBuilder();

while(s = reader.readLine() != null){

sb.append(s);

}

如果需要保留文本中的:\r\n 则不能使用BufferedReader

InputStreamReader reader = new InputStreamReader(new FileInputStream(“D:\\test.txt”),”UTF-8″);

StringBuilder sb = new StringBuilder();

byte [] buff = new byte[2048];

int length = 0;

while(-1 != (length = reader.read(buff))){

sb.append(new String(buff,0,length));

}



版权声明:本文为Amoon_原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。