上传一个文件 并保存至本地 java
时间: 2024-05-14 20:12:55 浏览: 6
以下是一个示例代码,用于上传文件并将其保存到本地文件系统中:
```java
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
public class FileDownloader {
public static void main(String[] args) {
String fileUrl = "http://www.example.com/myfile.txt";
String localFilePath = "C:/downloads/myfile.txt";
try {
URL url = new URL(fileUrl);
URLConnection conn = url.openConnection();
InputStream in = conn.getInputStream();
OutputStream out = new FileOutputStream(localFilePath);
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
in.close();
out.close();
System.out.println("File downloaded successfully!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在这个例子中,我们使用了`URL`和`URLConnection`类来打开指向远程文件的连接。然后,我们使用输入流从连接中读取文件的内容,并使用输出流将文件内容写入本地文件系统中。最后,我们关闭输入输出流并打印出下载完成的消息。请注意,您需要替换`fileUrl`和`localFilePath`变量的值以适应您的实际情况。