读取文件(FileInputStream)和写入文件(FileOutputStream)

读取文件(FileInputStream)和写入文件(FileOutputStream)

读取文件(FileInputStream)和写入文件(FileOutputStream)

使用程序复制文件
//输入文件操作对象
File read = new File("1.png");
//输出文件操作对象
File write = new File("2.png");
//输入文件流
InputStream inputStream = null;
//输出文件流
OutputStream outputStream = null;
try {
    inputStream = new FileInputStream(read);
    outputStream = new FileOutputStream(write);
} catch (FileNotFoundException e) {
    e.printStackTrace();
}
//返回指定的文件长度
byte[] bytes = new byte[(int) read.length()];
try {
    //将inputStream的数据转换成byte数组
    if (inputStream.read(bytes) != -1) {
        //将byte数组导入到outputStream中
        outputStream.write(bytes);
    }
    //关闭对象
    inputStream.close();
    outputStream.close();
} catch (IOException e) {
    e.printStackTrace();
        }
分段复制文件
//输入文件操作对象
File read = new File("1.png");
//输出文件操作对象
File write = new File("2.png");
//输入文件流
InputStream inputStream = null;
//输出文件流
OutputStream outputStream = null;
try {
    inputStream = new FileInputStream(read);
    outputStream = new FileOutputStream(write);
} catch (FileNotFoundException e) {
    e.printStackTrace();
}
byte[] bytes = new byte[514];
try {
    int date = 0;
    //将inputStream的数据转换成byte数组
    while ((date = inputStream.read(bytes)) != -1) {
        //将byte数组导入到outputStream中
        outputStream.write(bytes,0,date);
    }
    //关闭对象
    inputStream.close();
    outputStream.close();
} catch (IOException e) {
    e.printStackTrace();
        }