用java写一段代码,根据url下载文件
时间: 2023-03-14 18:19:06 浏览: 53
public static void downloadFile(String urlString) {
try {
URL url = new URL(urlString);
InputStream inputStream = url.openStream();
Files.copy(inputStream, Paths.get("下载的文件名"), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
}
相关问题
帮我用java写一段上传文件的代码
### 回答1:
以下是用Java写的上传文件的代码:// 导入必要的包
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;
// 创建URL对象
URL url = new URL("http://example.com/upload");
// 创建文件对象
File file = new File("file.txt");
// 创建HttpURLConnection对象
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
// 设置模式为上传模式
httpConn.setDoOutput(true);
httpConn.setRequestMethod("POST");
// 设置头信息
httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
// 获取文件的输入流
InputStream is = new FileInputStream(file);
// 读取输入流并写入到输出流中
OutputStream os = httpConn.getOutputStream();
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = is.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
// 关闭流
os.close();
is.close();
// 获取响应码
int responseCode = httpConn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// 处理响应
}
### 回答2:
当然可以帮你编写Java上传文件的代码。下面是一个简单的示例:
```java
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
@WebServlet("/upload")
@MultipartConfig
public class FileUploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 获取上传文件
Part filePart = request.getPart("file"); // "file"是上传表单中文件input的name属性值
String fileName = filePart.getSubmittedFileName();
// 设置保存目录
String savePath = "C:/uploads"; // 设置文件保存的目录
// 检查保存目录是否存在,不存在则创建
File directory = new File(savePath);
if (!directory.exists()) {
directory.mkdirs();
}
// 文件保存路径
String filePath = savePath + File.separator + fileName;
File savedFile = new File(filePath);
// 保存文件到服务器硬盘
try (InputStream input = filePart.getInputStream();
FileOutputStream output = new FileOutputStream(savedFile)) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = input.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
}
response.getWriter().println("文件上传成功!");
}
}
```
此示例展示了一个简单的Java Servlet,用于处理文件上传请求。在客户端的HTML代码中,你需要创建一个文件上传表单,其中`<form>`元素的`action`属性应指向该Servlet的URL。
在这个Servlet的`doPost()`方法中,我们首先从请求中获取文件的`Part`对象,然后使用`getSubmittedFileName()`方法获取上传文件的原始文件名。接下来,我们设置一个保存目录,并检查该目录是否存在,如果不存在则创建它。然后,我们使用文件保存路径创建一个新的`File`对象,并将文件的输入流复制到服务器硬盘中。
请注意,这只是一个简单的示例,仅用于向你展示如何使用Java处理文件上传。实际应用中,你可能还需要添加一些额外的逻辑来验证上传文件的类型、大小或其他验证规则,并处理可能出现的异常情况。
### 回答3:
当然可以帮您写一段用Java实现文件上传的代码。以下是一个简单的实例:
```java
import java.io.File;
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 FileUploader {
public static void main(String[] args) {
String fileUrl = "https://example.com/upload/file.txt"; // 要上传的文件的URL
String savePath = "C:/uploads/"; // 文件保存路径
try {
URL url = new URL(fileUrl);
URLConnection conn = url.openConnection();
String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
InputStream inputStream = conn.getInputStream();
File file = new File(savePath + fileName);
OutputStream outputStream = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
System.out.println("文件上传成功!");
inputStream.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在上面的代码中,我们首先指定了要上传的文件的URL(fileUrl),以及文件要保存到的路径(savePath)。
然后,我们使用Java的URL类和URLConnection类来打开指定URL的连接,并获取输入流,读取待上传的文件数据。
接着,我们通过输出流将文件写入本地磁盘的指定路径。
最后,关闭输入流和输出流,并打印出"文件上传成功!"的提示信息。
需要注意的是,上述代码中是进行单个文件的上传操作。如果需要实现同时上传多个文件,可以在代码中进行适当的修改。
希望以上代码对您有所帮助。如果您需要更复杂的文件上传功能或有任何其他问题,请随时告诉我。
java写一段文件上传的代码
好的,以下是Java写一段文件上传的代码示例:
```
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class FileUploader {
public static void main(String[] args) throws IOException {
String targetURL = "http://example.com/upload"; // 替换为实际的上传URL
String filePath = "path/to/file"; // 替换为实际的文件路径
File uploadFile = new File(filePath);
HttpURLConnection connection = null;
InputStream inputStream = null;
try {
// 创建连接
URL url = new URL(targetURL);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=---------------------------7da2137580612");
// 构建请求体
String boundary = "---------------------------7da2137580612";
String fileName = uploadFile.getName();
String body = "--" + boundary + "\r\n"
+ "Content-Disposition: form-data; name=\"file\"; filename=\"" + fileName + "\"\r\n"
+ "Content-Type: application/octet-stream\r\n\r\n";
byte[] bodyBytes = body.getBytes("UTF-8");
byte[] fileBytes = new byte[(int) uploadFile.length()];
inputStream = new FileInputStream(uploadFile);
inputStream.read(fileBytes);
byte[] endBytes = ("\r\n--" + boundary + "--\r\n").getBytes("UTF-8");
byte[] dataBytes = new byte[bodyBytes.length + fileBytes.length + endBytes.length];
System.arraycopy(bodyBytes, 0, dataBytes, 0, bodyBytes.length);
System.arraycopy(fileBytes, 0, dataBytes, bodyBytes.length, fileBytes.length);
System.arraycopy(endBytes, 0, dataBytes, bodyBytes.length + fileBytes.length, endBytes.length);
// 发送请求
connection.getOutputStream().write(dataBytes);
// 处理响应
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// 上传成功
System.out.println("上传成功");
} else {
// 上传失败
System.out.println("上传失败");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
if (inputStream != null) {
inputStream.close();
}
}
}
}
```
请注意将`targetURL`和`filePath`替换为实际的值,并确保请求头中的`boundary`值与请求体中的分隔符一致。此代码只是一个示例,具体实现可能因情况而异。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)