java 多线程 文件传输 代码
时间: 2024-03-15 18:40:23 浏览: 14
Java是一种广泛使用的编程语言,支持面向对象的编程范式。它具有跨平台性和可移植性,被广泛应用于各种应用程序开发领域。
多线程是Java中的一个重要特性,它允许程序同时执行多个任务,提高了程序的并发性和效率。在Java中,可以通过继承Thread类或实现Runnable接口来创建线程。以下是一个简单的多线程文件传输的示例代码:
```java
import java.io.*;
public class FileTransfer implements Runnable {
private String sourceFile;
private String destinationFile;
public FileTransfer(String sourceFile, String destinationFile {
this.sourceFile = sourceFile;
this.destinationFile = destinationFile;
}
@Override
public void run() {
try {
File file = new File(sourceFile);
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(destinationFile);
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
fos.write(buffer, 0, length);
}
fis.close();
fos.close();
System.out.println("文件传输完成!");
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String sourceFile = "source.txt";
String destinationFile = "destination.txt";
Thread thread = new Thread(new FileTransfer(sourceFile, destinationFile));
thread.start();
}
}
```
以上代码创建了一个名为FileTransfer的类,实现了Runnable接口,并重写了run方法。在run方法中,通过FileInputStream和FileOutputStream实现文件的读取和写入操作。在main方法中,创建了一个线程并启动,实现了文件的多线程传输。