字节输入流转为字符输入流
/** * 字节输入流转为字符输入流 */ public static void main(String[] args) { //创建文件对象,指定要读取的文件路径 File file=new File("d:\readme1.txt"); try { //创建文件字节输入流对象 FileInputStream fin=new FileInputStream(file); //创建字节缓冲区输入流对象,加快读取的效率 BufferedInputStream bin=new BufferedInputStream(fin); //创建缓冲区字符输入流对象"utf-8"表示读取的文本文件的字符编码格式 BufferedReader br=new BufferedReader(new InputStreamReader(bin, "utf-8")); String s=null; while((s=br.readLine())!=null){ System.out.println(s); } br.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
将字节输出流转为字符输出流
/** *将字节输出流转为字符输出流 *并指定字符编码格式为utf-8 */ public static void main(String[] args) { //创建文件对象指定文件的输出路径 File file=new File("d:\test.txt"); try { //创建文件字节输出流对象 FileOutputStream fout=new FileOutputStream(file,true); //创建缓冲区字节输出流对象 BufferedOutputStream bout=new BufferedOutputStream(fout); //创建字符缓冲区输出流对象"utf-8"表示输出的字符编码格式 BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(bout, "utf-8")); Scanner sc=new Scanner(System.in); System.out.println("请输入4句要保存的信息:"); String s=""; int i=0; while(i<4){ s+=sc.next()+" "; i++; } bw.write(s); bw.flush(); bw.close(); System.out.println("输出完成!"); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }