编写Java程序,使用 Java 的 I/O 流将 H:\eclipse.zip 文件拷贝至 E 盘下,重新命名为 eclipse 安装 .zip。
查看本章节
查看作业目录
需求说明:
使用 Java 的 I/O 流将 H:\eclipse.zip 文件拷贝至 E 盘下,重新命名为 eclipse 安装 .zip。在拷贝过程中,每隔2000 毫秒显示一次文件已经被拷贝的大小及剩余的大小,直至文件完成拷贝,提示用户文件已经拷贝完成
实现思路:
- 创建 InstantThread 类,该类需要继承 Thread 类
- 在 InstantThread 类中创建两个 File 类型的静态实例 readFile(被拷贝的文件)和 writeFile(拷贝后的文件)
- 在 InstantThread 类中定义 void copy(File readFile,File writeFile) 方法,完成文件的拷贝操作,参数readFile 表示要读取的文件,参数 writeFile 表示重新写入的新文件
- 重写 InstantThread 类的 run() 方法,该方法用于显示文件拷贝的进度。 在 run() 方法中调用 readFile 的 length() 方法以获取源文件的大小,并保存到 long 类型的变量 length 内
- 当变量 currentLength 的值大于等于 length 变量值时,结束循环
实现代码:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class InstantThread extends Thread{
final static File readFile = new File("D:\\1.rar");
final static File writeFile = new File("E:\\1.rar");
@Override
public void run() {
//被拷贝文件的大小
long length = readFile.length();
System.out.println("被拷贝的文件大小:"+length+"B");
while (true) {
try {
sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
long currentLength = writeFile.length();
System.out.println("已拷贝:"+currentLength+"B");
System.out.println("剩余:"+(length - currentLength)+"B");
if (currentLength>=length) {
System.out.println("文件已经完成拷贝");
break;
}
}
}
public void copy(File in,File ot) throws IOException {
FileInputStream input = new FileInputStream(in);
FileOutputStream ouput = new FileOutputStream(ot);
int data = 0;
while ((data = input.read())!=-1) {
ouput.write(data);
}
input.close();
ouput.close();
}
public static void main(String[] args) {
InstantThread i = new InstantThread();
i.start();
try {
i.copy(readFile, writeFile);
} catch (IOException e) {
e.printStackTrace();
}
}
}
本文来自博客园,作者:明金同学,转载请注明原文链接:https://www.cnblogs.com/vmuu/p/15663500.html
公众号:【明金同学】