IO流(6)—转换流
来源:互联网 发布:苹果mac系统更新macos 编辑:程序博客网 时间:2024/06/13 07:13
1.处理流之二:转换流
- InputStreamReader和OutputStreamWriter
2.当作用的文件就是一个文本文件且使用字节流传输时,需要把它转换成字符流,再在外面加上缓冲流以加速传输,比如:从键盘输入System.in默认是字节流,此时就可以考虑把字节流转换成字符流,效率更高。
3.转换流提供了在字节流和字符流之间转换
4.当字节流中都是字符时转换成字符流操作更高效
- 编码:字符串——>字符数组
解码:字符数组——>字符串
注:解码和编码时要使用同种编码方式,当文件中含有中文、英文时使用utf-8,全部为中国文时使用GBK,否则会有局部乱码
5.代码实例
public class InputOutputStreamReaderWriter { //将hello.txt文件,先解码成字符串,再编码成文本文件 @Test public void testInputOutputStreamReaderWriter(){ //4.定义缓冲流对象, BufferedReader br = null; //4.定义缓冲流对象, BufferedWriter bw = null; try { //解码 //1.定义文件对象 File file1 = new File("file/hello.txt"); //2.定义字节流对象 FileInputStream fis = new FileInputStream(file1); //3.定义转换流对象 InputStreamReader isr = new InputStreamReader(fis,"utf-8"); br = new BufferedReader(isr); //编码 //1.定义文件对象 File file2 = new File("file/hello3.txt"); //2.定义字节流对象 FileOutputStream fos = new FileOutputStream(file2); //3.定义转换流对象 OutputStreamWriter osw = new OutputStreamWriter(fos,"utf-8"); bw = new BufferedWriter(osw); //5.开始转化 String str; while((str = br.readLine()) != null){ bw.write("--"+str); bw.newLine(); bw.flush(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ if(bw != null){ try { bw.close(); } catch (IOException e) { e.printStackTrace(); } } if(bw != null){ try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } }}
阅读全文
0 0
- IO流(6)—转换流
- IO—转换流
- IO数据类型转换流
- 关于IO转换流
- IO之转换流
- Java IO 转换流
- io转换流
- IO类:转换流
- IO转换流
- IO之转换流
- Java IO 转换流
- IO流(字符流:转换流)
- IO流详解(三)转换流
- JAVA学习—IO—转换流
- 24.IO学习——转换流
- IO——转换流之BufferedReader
- 史上最全IO框架四(转换流)
- IO技术(四)转换流
- SwipRecyclerView原理探究
- Count Primes
- 怎么用IDEA上传本地项目到码云/Github?
- C语言数组
- 计蒜客 元素移除
- IO流(6)—转换流
- shell中各种括号的作用()、(())、[]、[[]]、{}
- 《春风十里不如你》身体骚动的魔性,精神成长的传记
- go get code.google.com/p/go.net/websocket失败
- 一种简单交换排序
- 使用 NLTK 对文本进行清洗,索引工具
- 面向对象的概念 | 类与对象 | java基础
- BFS E题
- 7种深度学习工具介绍