什么是IO?
IO是输入(input)和输出(output)的简写,IO技术主要用于处理设备之间的数据传输,其主要的设备是管道、网络连接与文件。对于程序本身来说,从外部数据存入内存中成为输入,那么从内存中释放到外部则称为输出。
一、什么是流?什么是IO流?
流:流是一种比较抽象的概念,与生活中的管道类似,是把一个地方的水运输到另一个地方。是内存与外部设备之间进行数据传输的通道。
IO流:IO中运用流来进行内存与外部设备之间的传输,所以称为IO流。
二、IO流的分类
IO流主要的分类方式有以下3种:
1、按数据流的方向:输入流、输出流。
2、按处理数据单位:字节流(一个byte)、字符流(两个byte)。
3、按流的功能来分:节点流(直接从数据源或目的地读写数据)、处理流(不直接连接到数据源或目的地,而是连接在已经存在的流)。
三、输入流、输出流
(1)InputStream和Reader是所有输入流的基类,OutputStream和Writer是所有输出流的基类。
(2)InputStream和OutputStream是字节流的抽象父类,以字节为单位进行操作,Reader和Writer是字符流的抽象父类,以字符为单位进行操作。
四、InputStream类和Reader类与OutputStream类和Writer类
(1)InputStream类:
int read();
int read(byte[ ] b);
int read(byte[ ] b,int off , int len );
public void close() throws IOException{}
(2)Reader类:
int read();
int read(char [ ] cbuf);
int read(char [ ]cbuf,int off , int len);
public void close() throws IOException{}
(3)OutputStream类
void write(int b);
void write(byte[ ] b);
void write(byte[ ] b , int off, int len);
public flush( ) throws IOException;
public void close( ) throws IOException;
(4)Writer类
void write(int c );
void write(char[ ] cbuf);
void write(char[ ]cbuf, int off, int len);
void write(String str);
void write(String str, int off, int len);
void flush( );
public void close( ) throws IOexception;
五、文件案例实例
package Steam;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public class IOsteam {
public static void main(String[] args){
String src = "//Users//liuhy//Desktop//1.txt";
String dest = "//Users//liuhy//Desktop//copy.txt";
test(src,dest,1024);
}
public static void test(String src,String dest,int map){
FileInputStream fit = null;
FileOutputStream fot = null;
try {
fit = new FileInputStream(src);
fot = new FileOutputStream(dest);
byte[] bytes = new byte[map];
while(fit.read(bytes) != -1){
fot.write(bytes);
fot.flush();
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try{
fot.close();
}catch (Exception e){
e.printStackTrace();
}
try{
fit.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
}
拢共分为打开流、操作流、关闭流,三个步骤。且必须要先开后关、后开先关。