1 前言
从网上获取资源是一种很常见的场景,比较从某个网站获取资料。
2 三种方式
2.1 Java NIO
代码如下:
代码语言:javascript复制URL website = new URL("https://www.nnjskz.com");
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream("a.html");
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
2.2 另一种NIO
代码如下:
代码语言:javascript复制URL website = new URL("https://www.nnjskz.com");
try (InputStream in = website.openStream()) {
Files.copy(in, Paths.get("a.html"), StandardCopyOption.REPLACE_EXISTING);
}
2.3 Apache Commons IO
引入依赖:
代码语言:javascript复制<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
代码如下:
代码语言:javascript复制URL website = new URL("https://www.nnjskz.com");
FileUtils.copyURLToFile(website, new File("a.html"));
总结
更多请参考How to download and save a file from Internet using Java?。