IO File Operations in Java II: File Read-Write Copy

Time:2019-10-9

Today, this article is mainly about the simple read-write copy of files, read from one file to write to another.


package com.lsl.readAndwrite;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class Test {
    public static void main(String[] args) {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        File startfile = new File ("D:\ book\ book\ 1. txt"); // Define an object for a source file
        File goalfile = new File ("D:\ book book\ 3. txt"); // Define an object to receive a file

        try {
            FileInputStream fis = new FileInputStream(startfile);
            bis = new BufferedInputStream(fis);
            bos = new BufferedOutputStream(new FileOutputStream(goalfile));
            byte[] bytes = new byte[1024];
            while (fis.read(bytes) != -1) {
                bos.write(bytes);
            }
            bos.flush();
            bos.close();
            fis.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            System.out.println ("D:\ book book\ 1.txt does not exist");
            System.out.println(-1);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}