I/O流概述
大多数应用程序都需要实现与设备之间的数据传输,在Java中,将这种通过不同输入输出设备(键盘,内存,显示器,网络等)之间的数据传输抽象表述为 “流”,程序运行通过流的方式与输入输出设备进行网络传输。
I/O流按照不同分类方式分为以下:
-
字节流和字符流
根据流操作的数据单位不同,可以分为字节流和字符流。字节流以字节为单位进行数据的读写,每次读写一个或多个字节;字符流以字符为单位进行数据的读写,每次读取一个或多个字符。
-
输入流和输出流
根据流传输方向的不同,又可以分为输入流和输出流。其中输入流只能从流中读取数据,而不能向流中写入数据,输出流则相反。
字节流
在计算机中,无论是文本,图片,音频还是视频,所有文件都是以二进制(字节)形式存在的,I/O流中针对字节的输入输出提供了一系列的流,统称为字节流。在JDK中,提供了两个抽象类InputStream和OutputStream,它们是字节流的顶级父类,所有的字节输入流都继承自InputStream,所有的字节输出流都继承OutputStream。这两个抽象类无法被实例化,所以通过它们的子类进行IO流操作。
-
字节流读写文件
//读取文件的数据 public class Demo01 { public static void main(String[] args) throws Exception{ InputStream in =new FileInputStream("src/test"); // byte[]buffer=new byte[1024]; // String ss=""; int b=0; while ((b=in.read(buffer))!=-1){ // ss=new String(buffer,0,b,"GBK"); // System.out.println(ss); System.out.println(b);//如果不对读取的数据进行处理,输出字节所对应的ASCII码值 } //关闭流 in.close(); } } //向文件中输入数据,但是会覆盖之前的数据 public class Demo02 { public static void main(String[] args) throws Exception{ OutputStream out=new FileOutputStream("src/test"); String str="world"; //将字符串转换为字节数组进行写入操作 out.write(str.getBytes()); out.close(); } } //向文件中输入数据,不覆盖之前的数据 public class Demo03 { public static void main(String[] args) throws Exception { //通过FileOutputStream构造方法FileOutputStream(String filename,bollean append)把append设置为true FileOutputStream out=new FileOutputStream("src/test",true); String str="world"; out.write(str.getBytes()); try { }catch (Exception e){ }finally { out.close();//就是不管程序有没有异常,都要关闭流 } } }
-
文件的拷贝
public class Demo04 { public static void main(String[] args) throws Exception { //创建文件输入流对象读取指定目录下的文件 FileInputStream in=new FileInputStream("src/test"); //创建文件输出流对象将读取到的文件内容写入到指定目录文件中 FileOutputStream out=new FileOutputStream("src/test2"); int len=0; long beginTime=System.currentTimeMillis(); while