LarryDpk
发布于 2024-03-16 / 1173 阅读
0

Java从网上下载文件的几种方式

1 前言

从网上获取资源是一种很常见的场景,比较从某个网站获取资料。

2 三种方式

2.1 Java NIO

代码如下:

URL website = new URL("https://www.pkslow.com");
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream("pkslow.nio.html");
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);

2.2 另一种NIO

代码如下:

URL website = new URL("https://www.pkslow.com");
try (InputStream in = website.openStream()) {
  Files.copy(in, Paths.get("pkslow.nio2.html"), StandardCopyOption.REPLACE_EXISTING);
}

2.3 Apache Commons IO

引入依赖:

<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.6</version>
</dependency>

代码如下:

URL website = new URL("https://www.pkslow.com");
FileUtils.copyURLToFile(website, new File("pkslow.commonsIO.html"));

总结

这里简单的展示几种方式,更多请参考How to download and save a file from Internet using Java?