进阶day09-文件复制实现(2种方式)

This commit is contained in:
2026-03-21 13:55:06 +08:00
parent 8f31c94ed8
commit d1108fcf1f
2 changed files with 62 additions and 0 deletions

View File

@@ -0,0 +1,31 @@
package com.inmind.inputstream02;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/*
一次读取一个字节,实现文件的复制
FileInputStream(String name) 通过打开与实际文件的连接来创建一个 FileInputStream ,该文件由文件系统中的路径名 name命名。
int read() 从该输入流读取一个字节的数据。返回值就是字节数据
FileOutputStream(String name) 创建文件输出流以指定的名称写入文件。
void write(int b) 将指定的字节写入此文件输出流。
*/
public class Test08 {
public static void main(String[] args) throws IOException {
//创建流对象(输入,输出)
FileInputStream fis = new FileInputStream("D:\\io_test\\upload\\1.jpg");
FileOutputStream fos = new FileOutputStream("D:\\io_test\\upload\\2.jpg");
//不停地读取一个字节,写出一个字节,直到读完
int c;//保存读取的字节
while ((c = fis.read()) != -1) {
//写出1个字节
fos.write(c);
}
//释放资源
fis.close();
fos.close();
}
}

View File

@@ -0,0 +1,31 @@
package com.inmind.inputstream02;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/*
一次读取一个字节数组,实现文件的复制
FileInputStream(String name) 通过打开与实际文件的连接来创建一个 FileInputStream ,该文件由文件系统中的路径名 name命名。
int read(byte[] b) 从字节输入流中将字节数据读取到参数b数组中返回的值读取的字节个数
FileOutputStream(String name) 创建文件输出流以指定的名称写入文件。
void write(byte[] b, int off, int len) 将 len字节从指定的字节数组开始从偏移量 off开始写入此文件输出流。
*/
public class Test09 {
public static void main(String[] args) throws IOException {
//创建流对象(输入,输出)
FileInputStream fis = new FileInputStream("D:\\io_test\\upload\\1.jpg");
FileOutputStream fos = new FileOutputStream("D:\\io_test\\upload\\3.jpg");
//不停地读取一个字节数组,写出一个字节数组,直到读完
int len;//保存读取到的字节的个数
byte[] bytes = new byte[1024];
while ((len = fis.read(bytes)) != -1) {
fos.write(bytes,0,len);//读多少个字节,一次性写出多少个字节
}
//资源释放
fis.close();
fos.close();
}
}