字节流
来源:互联网 发布:三观不正的日剧知乎 编辑:程序博客网 时间:2024/06/08 13:11
字节流的输入输出类为InputStream和OutputStream这两个类均为抽象类。而FileInputStream和FileOutputStream分别继承了这两个抽象方法,并且他们的主要方法为int read(buffer[],int off,int len)和void write(buffer[],int off,int len)、close()。这些方法均声明了异常抛出,因此在使用时都需要接收异常并处理。下面的代码为将F:/src目录下的f.txt文件内容传输到F:src目录下t.txt文件的实例。
//导入io类库import java.io.*;public class TestDemo{ public static void main(String args[]){ //创建一个FileInputStream引用 FileInputStream fis = null; //创建一个FileOutputStream引用 FileOutputStream fos = null; //由于构造函数声明了异常抛出throws FileNotFoundException,因此这里需要用try catch接收异常并处理 try{ //对fis引用创建实例对象,需要注意的是这里的文件路径需要用/而不是\符号 fis = new FileInputStream("F:/src/f.txt"); fos = new FileOutputStream("F:/src/t.txt"); //创建一个长度为100的字节数组接收传输内容,这里并不是说f.txt文件只有100个字节数,而是每次接收100个字节并传输,直到传输完毕为止。 byte buffer[] = new byte[100]; //定义一个int变量接收read的返回值,返回值为取到数据的大小。 int temp = 0; while(true){ //调用FileInputStream的int read(buffer,off,len)方法,这里的buffer表示接收数组,off表示从数组的第几位写入,len表示一次接收多少位。 temp = fis.read(buffer,0,buffer.length); //如果不能接收到数据那么read方法会返回一个-1,利用这一点来跳出循环。 //API文档的解释the total number of bytes read into the buffer, or -1 if there is no more data because the end of the file has been reached. if(temp == -1){ break; } //调用FileInputStream的int write(buffer,off,len)方法。参数与read方法一样。 fos.write(buffer,0,temp); } }catch(Exception e){ System.out.println(e); }finally{ //由于关闭字符流方法也声明了异常抛出 throws IOException因此也需要接收异常并处理。 try{ fis.close(); fos.close(); }catch(Exception e){ System.out.println(e); } } }}
0 0