标签:imp pac 读取数据 cep 输出流 str 构建 writer pre
1.为什么字符流和字节流需要转换?
这是因为有一些时候系统给你提供的只有字节流,比如说System.in标准输入流。就是字节流。你想从他那里得到用户在键盘上的输入,只能是以转换流将它转换为Reader以方便自己的程序读取输入。再比如说Socket里的getInputStream()很明显只给你提供字节流,你要不行直接用,就得给他套个InputStreamReader()用来读取。网络传输来的字符。
2.字节流和字符流怎么转换?
2.1.字节流转换为字符流:InputStreamReader
2.2.字符输流转换为字节流:InputStreamWriter
3.具体应用
3.1 字节流转换为字符流
package se.io; import java.io.*; public class InputStreamReaderTest { public static void main(String[] args) { try { //构建字节输入流对象 FileInputStream fileInputStream = new FileInputStream("E:\\test\\data3.txt"); //构建字节字符转换流对象 InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream); //构建字符输入流对象 BufferedReader bufferedReader = new BufferedReader(inputStreamReader); //读取数据 char[] chars = new char[1024]; int off = 0; while(bufferedReader.ready()){ off = bufferedReader.read(chars); } //打印输出 String s = new String(chars,0,off); System.out.println(s); //关闭流 bufferedReader.close(); inputStreamReader.close(); fileInputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
3.2字符流转换为字节流
package se.io; import java.io.*; public class OutPutStreamWriterTest { public static void main(String[] args) { try { //构建输出流字节对象 FileOutputStream fileOutputStream = new FileOutputStream("E:\\test\\data4.txt"); //构建输出流字节字符转换对象 OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream); //构建字符输出流对象 BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter); //构建数据 char[] chars = new char[3]; chars[0] = ‘a‘; chars[1] = ‘b‘; chars[2] = ‘中‘; //输出数据 bufferedWriter.write(chars); //关闭流 bufferedWriter.close(); outputStreamWriter.close(); fileOutputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
标签:imp pac 读取数据 cep 输出流 str 构建 writer pre
原文地址:http://www.cnblogs.com/wwyx-xi/p/7514196.html