在Java中,可以使用java.net
包中的类来实现文章长传和下载。
文章上传:
- 创建一个URL对象,指定要上传的文件的URL。
- 使用URLConnection类的
openConnection()
方法打开与URL的连接。 - 设置URLConnection对象的一些属性,例如设置请求方法为POST,启用输出流等。
- 使用URLConnection对象的
getOutputStream()
方法获取输出流,并将要上传的文件写入输出流中。 - 关闭输出流,完成上传操作。
URL url = new URL("http://example.com/upload");
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
OutputStream outputStream = connection.getOutputStream();
InputStream fileInputStream = new FileInputStream("file.txt");
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
fileInputStream.close();
文章下载:
- 创建一个URL对象,指定要下载的文件的URL。
- 使用URLConnection类的
openConnection()
方法打开与URL的连接。 - 使用URLConnection对象的
getInputStream()
方法获取输入流,并将输入流中的内容写入目标文件中。 - 关闭输入流,完成下载操作。
URL url = new URL("http://example.com/download/file.txt"); URLConnection connection = url.openConnection(); InputStream inputStream = connection.getInputStream(); OutputStream fileOutputStream = new FileOutputStream("file.txt"); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { fileOutputStream.write(buffer, 0, bytesRead); } fileOutputStream.close(); inputStream.close();