一:IO流用来处理数据之间的传输,Java对数组的数据是用流的方式,Java用于操做流在IO包中 二:流能够分为输入流,和输出流数组
三:操做类型能够分为:①字节流字节流能够操做任何数据,由于计算机中任何数据都是以字节存在的 ②:字符流能够操做存在的字符流,这样比较方便缓存
四:IO流的分类 ①InputStream ②OutputStream 字符流的抽象对象 Reader Writerbash
五:IO程序的书写 ①使用前,导IO包 ②使用时进行IO异常处理 ③使用后释放资源spa
//建立输入流对象
FileInputStream fs=new FileInputStream(“bb.txt”);
int b;
//读流的过程
while((b=fs.read())!=-1){
System.out.print(b);
}
//切记要记得关流
fs.close();
复制代码
为啥要用int值去接受code
由于输入流能够操做任意文件,包括图片,音频等,这些文件都是已二进制形式存储在,若是每一次读取文件都是返回的11111111,是-1的补码就会中止不读了,后面的数据读不到,因此就用int数据去接受。cdn
//在开发中不推荐使用
//建立输入输出对象
FileInputStream fis=new FileInputStream("E\\a.txt");
FileOutputStream fos=new FileOutputStream("E:\\b.txt");
//把要读取的数据放在数组中
byte by= new byte[fis.available];
//读文件
fis.read(by);
//写文件
fos.write(by);
fis.close();
fos.close();
复制代码
//建立字符缓冲流
BufferedInputStream bri=new BufferedInputStream(new FileInputStream("aa.txt"));
BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream("bb.txt"));
int c;
while((c=bri.read())!=-1){
bos.write(c);
}
bri.close();
bos.close();
复制代码
//close具备刷新功能,在关闭流以前,就会先刷新一次缓冲区,将缓冲区字节所有都刷新在缓冲区上,在关闭close刷完后不能写了
flush方法?
具有刷新功能,刷完后还能够继续写
FileInputStream filei = new FileInputStream("E:\\rec.avi");
//建立输出流对象
FileOutputStream fileo = new FileOutputStream("E:\\copy1.avi");
byte arr[]=new byte[1024*8];
int len;
while ((len=filei.read(arr))!=-1){
fileo.write(arr);
}
//close具备刷新功能,在关闭流以前,就会先刷新一次缓冲区,将缓冲区字节所有都刷新在缓冲区上,在关闭
filei.close();
fileo.close();
复制代码
在控制台输入文件路径, 将文件拷贝到当前目录下
复制代码
public static void main(String [] args){
//建立字符缓冲区
BufferedInputStream bis=new BufferedInputStream(new FileInputStream(getFile()));
BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(getFile().getName()));
int b;
while((b=bis.read())!=-1){
bos.write(b);
}
bis.close();
bos.close();
//用getFile方法区封装要获取的路劲
public static File getFile(){
Scanner sc=new Scanner(System.in);
System.out.print("重键盘上输入路径");
while(true){
String line=sc.nextLine();
File dir=new File(line);
//增长程序的鲁邦性
if(!dir.exists()){
System.out.print("你输入的路径不存在");
}else if(dir.isDirectory){
System.out.print("你输入文件目录,请从新输入");
}else{
retrun file;
}
}
}
}
}
复制代码