java i/o 流

一、理解java的I/O流:

java io包中 大体分两种流,1.字节流  2.字符流
在从功能分,有输入流(写出流),输出流(写入流)。

输入流就是从文件或者其他的介质中读取内容。(硬盘 → 内存,输入到内存,参照物是内存)

又称写出流(写出到硬盘,参照物是硬盘)。


输出流,就是从流中向文件或者其他介质写入内容。(内存 → 硬盘等,输出到内存)

又称写入流(写入到硬盘)

 

由上可见数据流的命名和流向是按照不同的参照物来划分的。

 

 二、字节流和字符流:

字节流操作的数据单元是字节,字符流操作的数据单元是字符。

 

1.inputStream 和 Reader是所有输入流的基类。

InputStream包含三个方法:

 

① int read():从输入流中读取单个字节;返回-1表示到了输入流的结束点。

public abstract int read()
                  throws IOException
Reads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.

A subclass must provide an implementation of this method.

 

Returns:
the next byte of data, or -1 if the end of the stream is reached.
Throws:
IOException - if an I/O error occurs.

 

 

②从输入流中读取最多len字节的数据,并将其存储在数组b中,放入b数组时,并不是从数组起点开始,而是从off位置开始,返回实际读取的字节数。返回-1表示到了输入流的结束点。

public int read(byte[] b,
                int off,
                int len)
         throws IOException
Reads up to len bytes of data from the input stream into an array of bytes. An attempt is made to read as many as len bytes, but a smaller number may be read. The number of bytes actually read is returned as an integer.

This method blocks until input data is available, end of file is detected, or an exception is thrown.

If b is null, a NullPointerException is thrown.

If off is negative, or len is negative, or off+len is greater than the length of the array b, then an IndexOutOfBoundsException is thrown.

If len is zero, then no bytes are read and 0 is returned; otherwise, there is an attempt to read at least one byte. If no byte is available because the stream is at end of file, the value -1 is returned; otherwise, at least one byte is read and stored into b.

The first byte read is stored into element b[off], the next one into b[off+1], and so on. The number of bytes read is, at most, equal to len. Let k be the number of bytes actually read; these bytes will be stored in elements b[off] through b[off+k-1], leaving elements b[off+k] through b[off+len-1] unaffected.

In every case, elements b[0] through b[off] and elements b[off+len] through b[b.length-1] are unaffected.

If the first byte cannot be read for any reason other than end of file, then an IOException is thrown. In particular, an IOException is thrown if the input stream has been closed.

The read(b, off, len) method for class InputStream simply calls the method read() repeatedly. If the first such call results in an IOException, that exception is returned from the call to the read(b, off, len) method. If any subsequent call to read() results in a IOException, the exception is caught and treated as if it were end of file; the bytes read up to that point are stored into b and the number of bytes read before the exception occurred is returned. Subclasses are encouraged to provide a more efficient implementation of this method.

 

Parameters:
b - the buffer into which the data is read.
off - the start offset in array b at which the data is written.
len - the maximum number of bytes to read.
Returns:
the total number of bytes read into the buffer, or -1 if there is no more data because the end of the stream has been reached.
Throws:
IOException - if an I/O error occurs.
NullPointerException - if b is null.

③从输入流中读取最多b.length个字节的数据,并将其存储在b中,返回实际读取的字节数。返回-1即到了输入流的结束点

public int read(byte[] b)
         throws IOException
Reads some number of bytes from the input stream and stores them into the buffer array b. The number of bytes actually read is returned as an integer. This method blocks until input data is available, end of file is detected, or an exception is thrown.

If b is null, a NullPointerException is thrown. If the length of b is zero, then no bytes are read and 0 is returned; otherwise, there is an attempt to read at least one byte. If no byte is available because the stream is at end of file, the value -1 is returned; otherwise, at least one byte is read and stored into b.

The first byte read is stored into element b[0], the next one into b[1], and so on. The number of bytes read is, at most, equal to the length of b. Let k be the number of bytes actually read; these bytes will be stored in elements b[0] through b[k-1], leaving elements b[k] through b[b.length-1] unaffected.

If the first byte cannot be read for any reason other than end of file, then an IOException is thrown. In particular, an IOException is thrown if the input stream has been closed.

The read(b) method for class InputStream has the same effect as:

 read(b, 0, b.length) 

 

Parameters:
b - the buffer into which the data is read.
Returns:
the total number of bytes read into the buffer, or -1 is there is no more data because the end of the stream has been reached.
Throws:
IOException - if an I/O error occurs.
NullPointerException - if b is null.

InputStream 和 Reader 都是抽象类,本身不能创建实例,

他们分别有一个用于读取文件的输入流,FileInputStream 和FileReader 。

 

FileInputStream示例:

public class FileInputStreamTest {
	public static void main(String[] args) throws IOException {
		FileInputStream fis = new FileInputStream("e:\\test.sql");
		//创建一个长度为1024的容器
		byte[] bbuf = new byte[1024];
		//用于保存容器中存储字节数实际长度
		int hasRead = 0;
		
		while((hasRead = fis.read(bbuf))>0){//每次循环都重新给hasRead赋值
			//将字节数组转换成字符串输入
			System.out.println(new String(bbuf,0,hasRead));
		}
		fis.close();
	}
}

 上例创建了一个长度1024的字节数组来读取该文件,实际上该文件的长度还不到1024字节,也就是说程序只需要执行一次循环即可读取全部内容,如果创建较小的字节数组,程序在输出中文时可能会初选乱码,引文文件保存的时候才用gbk的编码方式,每个中文字符占2个字节,如果字节数组将一个中文字符拆分进了2个数组,将会出现乱码。

 

FileReader示例:

public class FileReadTest {
	
	public static void main(String[] args) throws IOException {
		FileReader fr = null;
		try {
			fr = new FileReader("e:/test.sql");
			//创建一个长度为32位的"容器"
			char[] cbuf = new char[32];
			//容器中字符的位数
			int hasRead = 0;
			
			while((hasRead = fr.read(cbuf)) > 0){
				System.out.println(new String(cbuf,0,hasRead));
			}
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			fr.close();
		}
	}
}

 

 

Reader包含三个方法:

① int read():从输入流中读取单个字节;读不到返回-1

public int read()
         throws IOException
Read a single character.

 

Overrides:
read in class Reader
Returns:
The character read, or -1 if the end of the stream has been reached
Throws:
IOException - If an I/O error occurs

② 从输入流中读取最多

public int read(char[] b)
         throws IOException
Read a single character.

 

Overrides:
read in class Reader
Returns:
The character read, or -1 if the end of the stream has been reached
Throws:
IOException - If an I/O error occurs

public int read(char[] cbuf,
                int offset,
                int length)
         throws IOException
Read characters into a portion of an array.

 

Specified by:
read in class Reader
Parameters:
cbuf - Destination buffer
offset - Offset at which to start storing characters
length - Maximum number of characters to read
Returns:
The number of characters read, or -1 if the end of the stream has been reached
Throws:
IOException - If an I/O error occurs

 2.outputstream 和 Writer 输出流 。

两个输出流都提供了如下三个方法:

① void write(int c) 将指定的字节/字符输出到输出流中,c可代表字节、字符

② void write(byte[]/char[] buf)

叁 void write(byte[]/char[] buf, int off ,int len):将字节数组、字符数组中从off位置开始长度为len 的字符输出到指

定输出流中。

 

FileOutputStream示例:

public class FileOutputStreamTest {
	public static void main(String[] args) throws IOException {
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try{
			fis = new FileInputStream("e:\\test.sql");
			fos = new FileOutputStream("test1.sql");
			//创建一个长度为32byte的容器
			byte[] bbuf = new byte[32];
			//用于保存下面read方法的返回值
			int hasRead = 0;
			
			while((hasRead = fis.read(bbuf))>0){//每次循环都重新给hasRead赋值,0表示读完
				fos.write(bbuf);
			}
		}catch (Exception e) {
			e.printStackTrace();
		}	
		finally{
			if(fis != null){
				fis.close();
			}
			if(fos != null){
				fos.close();
			}
		}
	}
}

 FileWriter 示例:

public class FileWriterTest{
	public static void main(String[] args) throws IOException {
		FileWriter  fw = null;
		try {
			fw = new FileWriter("song.txt");
			fw.write("我们的家乡,\r\n");
			fw.write("在希望的田野上。\r\n");
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			fw.close();
		}
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值