Java IO3:字符流
字符流
字节流提供了处理任何类型输入/输出操作的功能(对于计算机而言,一切都是0 和1,只需把数据以字节形式表示就够了),但它们不可以直接操作Unicode字符,一个Unicode字符占用2个字节,而字节流 一次只能操作一个字节。既然Java的一个主要目的是支持“ 只写一次,到处运行” 的哲学,包括直接的字符输入/输出支持是必要的。字符流层次结构的顶层是Reader 和Writer 抽象类。
• 由于Java采用16位的Unicode字符,因此需要基于字符的输入/输出操作。从Java1.1版开始,加入了专门处理字符流的抽象类Reader和Writer,前者用于处理输入,后者用于处理输出。这两个类类似于InputStream和OuputStream,也只是提供一些用于字符流的规定,本身不能用来生成对象。
字节流一次处理一个字节,字符流一次处理一个字符。
• Java程序语言使用Unicode来表示字符串和字符,Unicode使用两个字节来表示一个字符,即一个字符占16位
Reader
Reader是定义Java的字符输入流的抽象类,该类的所有方法在出错的情况下都将引发IOException。Reader类中有这些方法:
/*** Abstract class for reading character streams. The only methods that a* subclass must implement are read(char[], int, int) and close(). Most* subclasses, however, will override some of the methods defined here in order* to provide higher efficiency, additional functionality, or both.*/ public abstract class Reader implements Readable, Closeable {/*** Attempts to read characters into the specified character buffer.* The buffer is used as a repository of characters as-is: the only* changes made are the results of a put operation. No flipping or* rewinding of the buffer is performed.*/public int read(java.nio.CharBuffer target) throws IOException {}/*** Reads a single character. This method will block until a character is* available, an I/O error occurs, or the end of the stream is reached.*/public int read() throws IOException {}/*** Reads characters into an array. This method will block until some input* is available, an I/O error occurs, or the end of the stream is reached.*/public int read(char cbuf[]) throws IOException {return read(cbuf, 0, cbuf.length);}/*** Reads characters into a portion of an array. This method will block* until some input is available, an I/O error occurs, or the end of the* stream is reached.*/abstract public int read(char cbuf[], int off, int len) throws IOException;/*** Skips characters. This method will block until some characters are* available, an I/O error occurs, or the end of the stream is reached.*/public long skip(long n) throws IOException {}/*** Tells whether this stream is ready to be read.*/public boolean ready() throws IOException {}/*** Closes the stream and releases any system resources associated with* it. Once the stream has been closed, further read(), ready(),* mark(), reset(), or skip() invocations will throw an IOException.* Closing a previously closed stream has no effect.*/abstract public void close() throws IOException; }
Writer
Writer是定义字符输出流的抽象类,所有该类的方法都返回一个void值并在出错的条件下引发IOException。Writer类中的方法有:
/*** Abstract class for writing to character streams. The only methods that a* subclass must implement are write(char[], int, int), flush(), and close().* Most subclasses, however, will override some of the methods defined here in* order to provide higher efficiency, additional functionality, or both.*/ public abstract class Writer implements Appendable, Closeable, Flushable {/*** Writes a single character. The character to be written is contained in* the 16 low-order bits of the given integer value; the 16 high-order bits* are ignored.*/public void write(int c) throws IOException {}/*** Writes an array of characters.*/public void write(char cbuf[]) throws IOException {write(cbuf, 0, cbuf.length);}/*** Writes a portion of an array of characters.*/abstract public void write(char cbuf[], int off, int len) throws IOException;/*** Writes a string.*/public void write(String str) throws IOException {write(str, 0, str.length());}/*** Writes a portion of a string.*/public void write(String str, int off, int len) throws IOException {}/*** Appends the specified character sequence to this writer.*/public Writer append(CharSequence csq) throws IOException {}/*** Appends a subsequence of the specified character sequence to this writer.*/public Writer append(CharSequence csq, int start, int end) throws IOException {}/*** Appends the specified character to this writer.*/public Writer append(char c) throws IOException {}/*** Flushes the stream. If the stream has saved any characters from the* various write() methods in a buffer, write them immediately to their* intended destination. Then, if that destination is another character or* byte stream, flush it. Thus one flush() invocation will flush all the* buffers in a chain of Writers and OutputStreams.*/abstract public void flush() throws IOException;/*** Closes the stream, flushing it first. Once the stream has been closed,* further write() or flush() invocations will cause an IOException to be* thrown. Closing a previously closed stream has no effect.*/abstract public void close() throws IOException;}
InputStreamReader和OutputStreamWriter类
• 这是java.io包中用于处理字符流的基本类,用来在字节流和字符流之间搭一座“桥”。这里字节流的编码规范与具体的平台有关,可以在构造流对象时指定规范,也可以使用当前平台的缺省规范
An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specified java.nio.charset.Charset charset. The charset that it uses may be specified by name or may be given explicitly, or the platform's default charset may be accepted.
An OutputStreamWriter is a bridge from character streams to byte streams: Characters written to it are encoded into bytes using a specified charset. The charset that it uses may be specified by name or may be given explicitly, or the platform's default charset may be accepted.
• InputStreamReader和OutputStreamWriter类的主要构造方法如下
– public InputSteamReader(InputSteam in)
– public InputSteamReader(InputSteamin,String enc)
– public OutputStreamWriter(OutputStream out)
– public OutputStreamWriter(OutputStream out,String enc)
• 其中in和out分别为输入和输出字节流对象,enc为指定的编码规范(若无此参数,表示使用当前平台的缺省规范,可用getEncoding()方法得到当前字符流所用
的编码方式)。
• 读写字符的方法read()、 write(),关闭流的方法close()等与Reader和Writer类的同名方法用法都是类似的。
public class StreamTest {public static void main(String[] args) throws Exception {//字节流FileOutputStream fos = new FileOutputStream("file.txt");//变成字符流OutputStreamWriter osw = new OutputStreamWriter(fos);//加上缓冲功能BufferedWriter bw = new BufferedWriter(osw);bw.write("http://www.google.com");bw.write("\n");bw.write("http://www.baidu.com");bw.close();FileInputStream fis = new FileInputStream("file.txt");InputStreamReader isr = new InputStreamReader(fis);BufferedReader br = new BufferedReader(isr);String str = br.readLine();while (null != str) {System.out.println(str);str = br.readLine();}br.close();} }
读取键盘输入
InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr);
FileReader和FileWriter
• FileReader类创建了一个可以读取文件内容的Reader类。 FileReader继承于InputStreamReader。 它最常用的构造方法显示如下
– FileReader(String filePath)
– FileReader(File fileObj)
– 每一个都能引发一个FileNotFoundException异常。这里, filePath是一个文件的完整路径,fileObj是描述该文件的File 对象
public class FileReader1 {public static void main(String[] args) throws Exception {File file = new File("c:\\CharSet.java");FileReader fr = new FileReader(file);BufferedReader br = new BufferedReader(fr);String str;while (null != (str = br.readLine())) {System.out.println(str);}br.close();} }
• FileWriter 创建一个可以写文件的Writer类。 FileWriter继承于OutputStreamWriter.它最常用的构造方法如下:
– FileWriter(String filePath)
– FileWriter(String filePath, boolean append)
– FileWriter(File fileObj)
– append :如果为 true,则将字节写入文件末尾处,而不是写入文件开始处
• 它们可以引发IOException或SecurityException异常。这里, filePath是文件的完全路径, fileObj是描述该文件的File对象。如果append为true,输出是附加到文件尾的。
• FileWriter类的创建不依赖于文件存在与否。在创建文件之前, FileWriter将在创建对象时打开它来作为输出。如果你试图打开一个只读文件,将引发一个IOException异常
public class FileWriter1 {public static void main(String[] args) throws IOException {String str = "hello world welcome nihao hehe";char[] buffer = new char[str.length()];str.getChars(0, str.length(), buffer, 0);FileWriter f = new FileWriter("file2.txt");for (int i = 0; i < buffer.length; i++) {f.write(buffer[i]);}f.close();} }
Java IO3:字符流相关推荐
- Java IO: 字符流的Buffered和Filter
作者: Jakob Jenkov 译者: 李璟(jlee381344197@gmail.com) 本章节将简要介绍缓冲与过滤相关的reader和writer,主要涉及BufferedReader.B ...
- Java IO: 字符流的Piped和CharArray
转载自 Java IO: 字符流的Piped和CharArray 作者: Jakob Jenkov 译者: 李璟(jlee381344197@gmail.com) 本章节将简要介绍管道与字符数组相 ...
- java binaryreader_Java字符流与字节流区别与用法分析
本文实例讲述了Java字符流与字节流区别与用法.分享给大家供大家参考,具体如下: 字节流与字符流主要的区别是他们的的处理方式 流分类: 1.Java的字节流 InputStream是所有字节输入流的祖 ...
- java中字符流和字节流的区别_java中字节流和字符流有哪些区别
java中字节流和字符流的区别有:1.定义不同:2.结尾不同:3.处理方式不同:4.缓冲区不同:5.编码方式不同.字节流默认不使用缓冲区,而字符流使用缓冲区.字节流采用ASCII编码,字符流采用uni ...
- java中字符流 字节流_理解Java中字符流与字节流的区别
1. 什么是流 Java中的流是对字节序列的抽象,我们可以想象有一个水管,只不过现在流动在水管中的不再是水,而是字节序列.和水流一样,Java中的流也具有一个"流动的方向",通常可 ...
- Java io字符流读入英文_Java IO 系列教程(四)-字符输入流(2)
本文介绍字符输入流 在前面一节中,我们向一个文件中写入了一些字符,通过图片可以看出总共是6个中文字符和一个换行,总共是20个字节,可以推算出字符编码是utf-8,每个汉子占3三个字节.本文就用字符输入 ...
- 在java中字符流怎么复制_Java 使用字符流拷贝数据
使用字符流拷贝数据时,需要注意在文件末尾处的数据,因为最后一次读取的长度不会刚好与数组input长度相同,所以需要引入新的变量来存储每次读取的长度. import java.io.File; impo ...
- java字节字符流实验报告_Java第09次实验(IO流)--实验报告
0.字节流与二进制文件 我的代码 用DataOutputStream和FileOutputStream将Student对象写入二进制文件student.data package test; impor ...
- java io字符流_Java IO流字符流简介及基本使用
Java IO流字符流简介及常用字符流的基本使用 字符流分为输入字符流(Writer)和输出字符流(Reader),这两种字符流及其子类字符流都有自己专门的功能.在编码中我们常用的输出字符流有File ...
- 【JAVA】-- 字符流(Reader、Writer)
InputStream和OutputStream类在读写文件时操作的都是字节,如果希望在程序中操作字符,则可以使用字符流:FileReader对象返回的字符流是char,而InputStream对象返 ...
最新文章
- 《Asp.Net 2.0 揭秘》读书笔记(五)
- 未来,让我们一起想象 — “Imagine” 阿里云视频云全景创新峰会
- 异常处理_月隐学python第19课
- # android开发:4-1、Activity启动方式、生命周期、不同activity的数据传递
- How to Install MariaDB 10 on CentOS 6.7
- Python 如何随机生成姓名?
- 透视投影中已知两平面的单应矩阵,能否求出这两平面的夹角?
- 如何配置Gitlab的双因子验证(Two-Factor Authentication)
- 水晶报表的宽度调整方法(设计器、代码调整、rpt文件属性)
- xyplorer设置备忘
- 武学大陆-为啥要学IT绝世武功
- 武汉科技大学计算机科学与技术分数,2019武汉科技大学研究生分数线汇总(含2016-2019历年复试)...
- PDF补丁丁( PDFPatcher.)
- VS C++学习笔记
- 服务器维护配件,服务器维修,服务器升级,服务器配件,磁盘柜维修及维护
- 将表格导出为excel
- 第四章 实验一 用类描述坦克
- 海思3559开发常识储备:相关名词全解
- 百度云网速慢?普通VIP也限速?用户激励措施太套路?Pandownload被举报?这些统统没关系,我们自己搭建一个私人云盘服务器
- 实现阿里云OSS文件上传
热门文章
- 网络人工智能研究方向有哪些?
- 人工智能重点领域有哪些呢?
- vue + typescript 父子组件传值记录
- JS -- http、https地址自动检测并添加为链接
- linux:记录一次 处理tomcat启动卡死无报错现象的曲折过程
- Android study week1
- java 合并排序算法、冒泡排序算法、选择排序算法、插入排序算法、快速排序...
- 关于Exchange Server 2010(WEB浏览证书)证书问题
- Matlab之eval函数
- findfont: Font family [‘Times New Roman‘] not found. Falling back to DejaVu Sans.