用java 写一个文件上传下载
时间: 2023-09-21 21:08:49 浏览: 46
以下是一个使用 Java 编写的文件上传和下载的示例:
文件上传:
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileUploadDemo {
public static void main(String[] args) {
String sourceFilePath = "path/to/source/file.txt";
String destinationFilePath = "path/to/destination/file.txt";
try {
// 读取源文件
File sourceFile = new File(sourceFilePath);
FileInputStream fileInputStream = new FileInputStream(sourceFile);
// 创建目标文件
File destinationFile = new File(destinationFilePath);
if (!destinationFile.exists()) {
destinationFile.createNewFile();
}
// 写入目标文件
FileOutputStream fileOutputStream = new FileOutputStream(destinationFile);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, bytesRead);
}
// 关闭流
fileInputStream.close();
fileOutputStream.close();
System.out.println("文件上传成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
文件下载:
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileDownloadDemo {
public static void main(String[] args) {
String sourceFilePath = "path/to/source/file.txt";
String destinationFilePath = "path/to/destination/file.txt";
try {
// 读取源文件
File sourceFile = new File(sourceFilePath);
FileInputStream fileInputStream = new FileInputStream(sourceFile);
// 创建目标文件
File destinationFile = new File(destinationFilePath);
if (!destinationFile.exists()) {
destinationFile.createNewFile();
}
// 写入目标文件
FileOutputStream fileOutputStream = new FileOutputStream(destinationFile);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, bytesRead);
}
// 关闭流
fileInputStream.close();
fileOutputStream.close();
System.out.println("文件下载成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
你需要将 `sourceFilePath` 替换为要上传/下载的源文件路径,将 `destinationFilePath` 替换为要上传/下载到的目标文件路径。
这个示例使用了 FileInputStream 和 FileOutputStream 来进行文件的读取和写入操作。通过读取源文件并将其内容写入目标文件,实现了文件的上传和下载。
希望这个示例对你有所帮助!如果有任何问题,请随时提问。