一:InputStream与OutputStream提供了输入输出流来对文件进行操作,可以用来处理二进制文件,也可以用来处理文本文件。
InputSteram提供的一些方法:
public void read();从输入流中读取一个字节
public int read(byte[] b);从输入流中读取最多b.length个字节,存入字节数组中
public int read(byte[] b,int off,int len);从输入流中读取最多len个字节,存入开始下标为off的字节数组中,
public int available();判断流是否做好读的准备
public long skip(long n);跳过输入流中的n个字节
public void mark();标记输入流的当前位置
public void reset();重定位输入流
public void close();关闭流
OutputStream提供的关闭流一些方法:
public void write(int b);
public void write(byte[] b);将字节数组b写入输出流
public void write(byte[] b,int off,int len);将字节数组b写入输出流(off表示起始偏移,len字节个数)
public void flush();强制清空缓冲区并执行向外设写操作
public void close();关闭流
这两类是抽象类,所以我们使用时,需使用实现它们的子类。
FileInputStream:文件输入流,它表示一个文件字节输入流,从中可读取一个字节或一批字节;
构造方法:
public FileInputStream(String name);以名为name的文件建立输入流
public FileInputStream(File file);已指定文件对象file建立输入流
FileOutputStream:文件输出流,它表示一个文件字节输出流,可向流中写入一个字节或一批字节。在生成FileOutputStream类对象时,若指定文件不存在,则创建一个新的文件,若存在,则清除文件内容。
构造方法:
public FileOutputStream(String name);以名为name的文件建立输出流
public FileOutputStream(String name,Boolean append);以名为name的文件建立输出流,当appen为true时,数据会从原有文件内容末尾开始写入
public FileOutputStream(File file);已指定文件对象file建立输出流
FileInputStream和FileOutputStream继承了对应的抽象类InputStream和OutputStream,因父类里的方法也都被继承了。
结果:public static void main(String[] srgs){ String path1 = "D:\\fileInputOutpuStreamTest\\abc.txt"; String path2 = "D:\\fileInputOutpuStreamTest\\abc2.txt"; FileInputStream fis = null;//声明文件输入流对象 FileOutputStream fops = null;//声明文件输出流对象 try { //创建文件输入流对象 fis = new FileInputStream(path1); //创建文件输出流对象 fops = new FileOutputStream(path2); //开始读,每次读的大小默认为1024个字节 byte[] b = new byte[1024]; int i = 0; //判断缓冲区返回数据是否已经到了结尾,如果结尾,则返回-1 while((i = fis.read(b)) != -1){ //为了知道我文件信息,我将每次读到的内容输出 System.out.print(new String(b)); //从字节数组b中将其实位置0,长度为i个字节的内容输出。 fops.write(b,0,i); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { try { if(fops != null) fops.close(); if(fis != null) fis.close(); } catch (IOException e) { e.printStackTrace(); } } }
控制台打印结果
复制后的文件及文件内容