流(IO---Input、output)

 

一、都是站在程序的立场。从程序读数据源就是Input,从程序写入数据源,就是output。这个数据源可以是文件、图片、视频、内存、网络等;
InputStream是一个抽象类
FileInputStream继承的是InputStream
FileInputStream fis=new FileInputStream("路径或者是文件对象---File"),使用时要导包,还要使用try...catch。----这就是搭建好了管道。
reader 字符流读 抽象类
writer 字符流写 抽象类

二、流的类型通常分为:
1、按照方向划分:输入流、输出流

2、按照类型划分:字节流(8位)
例子public class Test {

public static void main(String[] args) {

InputStream fis = null;
OutputStream fos = null;

try {
fis = new FileInputStream("c:\\test\\onepiece.jpg");
fos = new FileOutputStream("c:\\test1\\lufei.jpg");

byte [] bs = new byte[1024];

int len = 0;

while((len = fis.read(bs)) != -1) {
fos.write(bs, 0, len);
}


} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if(fis != null) fis.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(fos != null) fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

、字符流(16位)
例子:public class Test {

public static void main(String[] args) {

// Reader 字符流读 抽象类
// Writer 字符流写 抽象类
Reader r = null;

Writer w = null;
try {
r = new FileReader("Test1.txt");

w = new FileWriter("TestTest.txt");

char [] cs = new char[1024];
int len = 0;

while((len = r.read(cs)) != -1) {
String str = new String(cs,0,len);
System.out.println(str);

w.write(str);
}


} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if(r != null) r.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

try {
if(w != null) w.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

}
3、按照操作方式划分:
节点流---就从一个特定的数据源(节点)读取数据的流
过滤流--就相当于在原来的管道上套一根新管道添加一些功能
4、转换流
三、流的使用
.read()方法只能读取一个字节,其中能读取空格和回车
输出的时候如果文件不存在,就创建文件,没有文件夹不会自动创建,会报错
纯的文本用字符流
不是纯文本的用字节流
缓冲流BufferedInputStream(他可以是读取的速度加快),
在字符流中的reader有读取一行的方法,但不会读取换行符,所以要加上换行符。
我们在使用流的时候,都要关闭流,不然会造成内存溢出;而关闭一定要在finally中进行,这样无论正不正确有无异常都会关闭
如果管道没有关闭,会剩一部分在管道中没有读出,可以使用push()方法。

 

posted @ 2019-12-11 17:13  王刚a  阅读(908)  评论(0编辑  收藏  举报