Java复习7.输入输出流 20131005

前言:

Java中涉及数据的读写,都是基于流的,这一块的知识相当重要,而且在Java中的数据,char字符是16bit的,所以存在字节流和字符流的区别。如果是字符文件的输入输出,使用字符流(以Reader/Writer为抽象基类),而其他的数据是二进制的,需要使用字节流(以InputStream和OutputStream为抽象基类)。

其实不止文件,网络数据传输也是输入输出流。

目录

1.字节流和字符流... 2

1.1字节输入流:... 2

1.2字节输出流:... 5

2.字符流... 6

2.1字符数据流输入:... 6

2.2字符数据流输出:... 7

3.使用缓冲数据流,提高IO的效率,减少IO的次数... 7

3.1缓冲字节流: 8

3.2缓冲字符流:... 9

为了便于理解,附图一张:

 

1.字节流和字符流

字节流就是数据的基本单位是byte,字符流使用字符组成的,基本单位是char,在Java中char是由两个字节保存的。所有的InputStream/OutputStream的子类都可以用于处理二进制数据,他是按照字节存储的,但是对于字符的文本文件,使用字符流比较好。

首先是字节流,基类是InputStream/OutputStream

1.1字节输入流:

InputStream in = null;

try {

String filePath = ClassLoader.getSystemResource("a.txt").getPath();

System.out.println("FilePath:"+filePath);

/*

* 以字节流的方式打开文件,读取的是一个二进制流 byte[] ,如果不存在该文件,则会抛出异常,FileNotFoundException           *

*/

in = new FileInputStream(filePath);

byte[] buf = new byte[100];

// read file from inputstream

/*

* public int read(); read next byte data, if to the file end return -1;

* public int read(byte[] buf);

* Reads up to b.length bytes of data from this input stream into an array of bytes.

* return the total number of bytes read into the buffer, or -1 if there is no more data

* because the end of the file has been reached.

* we should clear the buf or record the read byte number.

*

*/

if(in != null){

/*

* 比较正规的读取方式,这样每一次获取的是一定字节数的byte,保存在响应的字节中,然后

* 将字节数组转换成String输出结果

*/

/*int read_byte_number = -1;

int count = 0;

while( (read_byte_number = in.read(buf, 0, 100)) != -1){

System.out.print(new String(buf,0,read_byte_number));

count++;

}

System.out.println("count:" + count);

*/

/*

*  在文件中的数据,一个ASCII对应的是一个字节,但是一个汉字或者其他的字符,保存在文件中是两个字节

*  我们读取的时候使用read只是读取的一个字节,所以对于ASCII的字符是可以读取出来的,返回值对应的ASCII的int

*  可以将它转换成相应的char;但是对于汉字是不可以的,每次只是读取的一个字符。

*/

int i = in.read();

System.out.println(i+":" + (char)i);

}

} catch (FileNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}finally{

if(in != null){

try {

in.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

1.2字节输出流:

OutputStream  out = null;

try {

/*

* if the file does not exist, it will create the file

* if the file exists, but append default is false, it will clear the file write new content

* we can use the parameter append = true to append context to the end

*/

out = new FileOutputStream("b.txt",true);

out.write('腾');

/*

* public void write(int b); 可以是一个char但是,如果在ASCII之外的字符,就只能写一byte结构很坑,不可预期

* public void write(byte[] buf);

* public void write(byte[] buf, int start, int length);

*/

} catch (FileNotFoundException e1) {

// TODO Auto-generated catch block

e1.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}finally{

if(out != null){

try {

out.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

2.字符流

使用字节流是不可以处理中文的,这样我们就必须使用字符流。字符流的基类是Reader/Writer

Reader BufferedReader

           InputStreamReader    FileReader

    Writer BufferedWriter

           OutputStreamWriter       FileWriter

           PrintWriter

这几个是常见的使用的。

2.1字符数据流输入:

Reader reader= null;

try {

reader = new FileReader(ClassLoader.getSystemResource("a.txt").getPath());

char[] buf  = new char[10];

int count = 0;

while((count = reader.read(buf,0,10)) != -1){

System.out.print(new String(buf,0,count));

}

/*

* use public int read() function return 0x0000~0xffff int value

*/

/*int a;

while((a=reader.read()) != -1){

System.out.println((char)a);

}

*/

} catch (FileNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}finally{

if(reader != null){

try {

reader.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

2.2字符数据流输出:

Writer out = null;

try {

// FileWriter(String filename, boolean append = false);

//FileWriter(File file, boolean append = false);

out = new FileWriter("a.txt",true);

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

char buf[] = {'杨','腾','飞','a','b','c'};

if(out != null){

try {

System.out.println(new String(buf,0,buf.length));

out.write(buf, 0, buf.length);

out.flush();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}finally{

if(out != null){

try {

out.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

}

3.使用缓冲数据流,提高IO的效率,减少IO的次数

2中的操作数据流的方法特别低效,不适合远程操作或者是大型项目,我们使用缓冲数据流提高IO的性能。

3.1缓冲字节流:

InputStream   FileInputStream

                  FilterInputStream  BufferedInputStream

    OutputStream  FileOutputStream

                  FilterOutputStream BufferedOutputStream  

将FileInputStream/FileOutputStream转换成

BufferedInputStream/BufferedOutputStream

BufferedInputStream bis = null;

try {

bis = new BufferedInputStream(new FileInputStream("a.txt"));

byte [] buf = new byte[10];

int count = -1;

while( (count = bis.read(buf, 0, 10)) != -1){

System.out.print(new String(buf,0,count));

}

} catch (FileNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}finally{

if(bis != null){

try {

bis.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

BufferedOutputStream bos = null;

try {

bos = new BufferedOutputStream(new FileOutputStream("b.txt",true));

byte[] buf = null;

String a = "杨腾飞a";

buf = a.getBytes();

bos.write(buf,0,buf.length);

bos.flush();

} catch (FileNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}finally{

if(bos != null){

try {

bos.flush();

bos.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

3.2缓冲字符流:

BufferedReader/BufferedWriter

BufferedReader breader = new BufferedReader(new FileReader(“filename”))

Example:

BufferedReader breader = null;

try {

breader = new BufferedReader(new FileReader("a.txt"));

char[] buf = new char[10];

int count = -1;

while( (count = breader.read(buf, 0, 10))  != -1){

System.out.print(new String(buf,0,count));

}

//每一次获取一行数据,当遇到行结束的时候,终止,返回的是一个字符串,但是不包含换行符。

/*

String a ;

while((a=breader.readLine()) != null){

System.out.println(a);

}

*/

} catch (FileNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

缓冲输出流的话,详细你也会了吧,就这样了

在Java 中的输入输出流是十分重要的一个知识点,后面的网络编程也是需要用到这些输入输出流。

追梦的飞飞

于广州中山大学 20131005

HomePage: http://yangtengfei.duapp.com

Java复习7.输入输出流的更多相关文章

  1. 第27章 java I/O输入输出流

    java I/O输入输出流 1.编码问题 import java.io.UnsupportedEncodingException; /** * java涉及的编码 */ public class En ...

  2. JAVA Io 缓冲输入输出流

    java中提供带缓冲的输入输出流.在打开文件进行写入或读取操作时,都会加上缓冲,提高了IO读写性能. 1. BufferedInputStream 缓冲输入流 2. BufferedOutputStr ...

  3. Java I/O输入输出流详解

    一.文件的编码               开发时一定要注意项目默认的编码!!!!!!!!               文件操作的时候一定要记得关闭!!!!!!!!        ASCII:美国标准 ...

  4. Java IO学习--输入输出流

    一.Java IO的定义 I/O:输入输出系统,由输入输出控制系统和外围设备两部分组成. Java中I/O操作主要是指使用Java进行输入,输出操作. Java所有的I/O机制都是基于数据流进行输入输 ...

  5. java实验8-Java输入输出流

    1 读写文件 [实验目的] (1)掌握文本文件的读写方法. (2)掌握随机文件的读写方法. (3)掌握InputStream.OutputStream抽象类的基本使用. (4)掌握FileInputS ...

  6. Java工具类-输入输出流

    输入输出流 1.概念 输入输出流:文件复制,上传 输出流: System.out.println() 写操作,程序将字符流写入到"目的地",比如打印机和文件等 输入流 :Scann ...

  7. java学习笔记-输入输出流

    ================File类 =====================InputStream ==================OutputStream ============== ...

  8. Java中的输入输出流

    FileInputStream和FileOutputStream 创建含磁盘文件的输入 输出流对象. FileInputStream继承自InputStream,用于读取本地文件中的字节数据,由于所有 ...

  9. 《三》Java IO 字节输入输出流

    那么这篇博客我们讲的是字节输入输出流:InputStream.OutputSteam(下图红色长方形框内),红色椭圆框内是其典型实现(FileInputSteam.FileOutStream)     ...

随机推荐

  1. java环境变量及Eclipse自动编译问题

    环境变量,是在操作系统中一个具有特定名字的对象,它包含了一个或者多个应用程序所将使用到的信息.例如Windows和DOS操作系统中的path环境变量,当要求系统运行一个程序而没有告诉它程序所在的完整路 ...

  2. iOS 总结APP间跳转的常用以及非常用需求 APP跳转Safari APP跳转APP

    需求驱动技术,有了新的需求,旧技术无法实现时,就会有新的技术出现. 一般的APP跳转需求有以下几种: 1.  从自己的APP跳转到别人的APP. 2. 从自己的APP跳转系统APP. 3. 让别人的A ...

  3. XSS是什么

    1.XSS是跨站脚本攻击(Cross Site Scripting),为不和层叠样式表(Cascading Style Sheets, CSS)的缩写混淆,故将跨站脚本攻击缩写为XSS. 2.恶意攻击 ...

  4. mongo启动

    mongo启动 删除data目录里的mongo.lock bin 目录里执行 net  start MongoDB

  5. Could not connect to '192.168.89.144' (port 22)

    xshell连接linux主机时,会出现错误:Could not connect to '192.168.89.144' (port 22): Connection failed. 但是这时能ping ...

  6. 简单的linux压力测试工具webbench

    wget http://blog.s135.com/soft/linux/webbench/webbench-1.5.tar.gz tar zxvf webbench-1.5.tar.gz cd we ...

  7. github代码上传下载慢问题

    绑上下面的host,实测下载速度可提高2倍左右. 151.101.72.249 github.global.ssl.fastly.net

  8. powershell 设置环境变量 -- go 单元测试 exit status 3221225781

    执行单元测试时出错 go test -run TestImage 错误提示如下: exit status 3221225781 这个错误的意思是需要加载对应的库文件找不到,加载对应的库文件就习. 但是 ...

  9. Android studio通过连接蓝叠模拟器大幅提高速度!

    因为我的电脑是X200,集成显卡,不支持Opengl 2.0,很多安卓模拟器都不能用(夜神.海马玩,mumu等)最后发现蓝叠. 首先WIN+R,CMD,输入ADB,如果没有命令信息,说明我们需要在PA ...

  10. 2017阿里C++研发工程师-校招-笔试模拟

    题目描述: 猎人把一对兔子婴儿(一公一母称为一对)放到一个荒岛上,两年之后,它们生00下一对小兔,之后开始每年都会生下一对小兔.生下的小兔又会以同样的方式继续繁殖. 兔子的寿命都是x(x>=3) ...