FileOutputStream

@Test
public void test4() {
    //1. 创建一个File对象,表明要写入的文件位置
    //输出的物理文件可以不存在,当执行过程中,不存在会自动创建
    File file = new File(\"hello3.txt\");
    //2. 创建一个FileOutputStream的对象,将file的对象作为形参传递给FileOutputStream的构造器中
    FileOutputStream fos = null;

    try {
        fos = new FileOutputStream(file);
        //3. 写入操作
        fos.write(new String(\"I love China\").getBytes());
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        //4. 关闭输出流
        if (fos != null){
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

从磁盘中复制文件

//从磁盘中读取一个文件,并写入到另一个位置(相当于文件的复制)
@Test
public void test5(){
    //1. 提供读入,写出的文件
    File file1 = new File(\"hello1.txt\");
    File file2 = new File(\"hello3.txt\");
    //2. 提供相应的流
    FileInputStream fis = null;
    FileOutputStream fos = null;

    try {
        fis = new FileInputStream(file1);
        fos = new FileOutputStream(file2);
        //3. 实现文件的复制
        byte[] b = new byte[5];
        int len;
        while ((len = fis.read(b))!= -1){
            fos.write(b,0,len);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        if (fos != null){
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (fis != null){
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

将文件中的地址转换为参数,可以实现文件的基本拷贝的方法

File file1 = new File(\"hello1.txt\");
File file2 = new File(\"hello3.txt\");

具体每次读取大小根据文件大小决定: byte[] b = new byte[5];

收藏 打印