Java代码如何将InputStream转换为File对象呢?
下文笔者讲述将InputStream转换为file对象的方法分享,如下所示
实现思路: 方式1: 将InputStream复制到FileOutputStream 方式2: 使用Apache Commons IO中的FileUtils.copyInputStreamToFile 方式3: 使用Java 1.7 NIO Files.copy例:inputstream转换为file对象的示例分享
InputStreamToFile.java package com.java265; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URI; public class InputStreamToFile { private static final String FILE_TO = "d:\\test\\test.txt"; public static void main(String[] args) throws IOException { URI u = URI.create("https://www.java265.com/"); try (InputStream inputStream = u.toURL().openStream()) { File file = new File(FILE_TO); copyInputStreamToFile(inputStream, file); } } // InputStream -> File private static void copyInputStreamToFile(InputStream inputStream, File file) throws IOException { try (FileOutputStream outputStream = new FileOutputStream(file)) { int read; byte[] bytes = new byte[1024]; while ((read = inputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, read); } } } }2. Apache Commons IO 2.1 FileUtils.copyInputStreamToFile在Apache Commons IO中可用 pom.xml <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.6</version> </dependency> InputStreamToFile2.java package com.java265; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URI; public class InputStreamToFile2 { private static final String FILE_TO = "d:\\test\\test.txt"; public static void main(String[] args) throws IOException { URI u = URI.create("https://www.java265.com/"); try (InputStream inputStream = u.toURL().openStream()) { File file = new File(FILE_TO); // commons-io FileUtils.copyInputStreamToFile(inputStream, file); } } } 3. Java 1.7 NIO 将inputStream保存到某个文件中 可使用Java 1.7 NIO Files.copy InputStreamToFile3.java package com.java265; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.nio.file.Files; import java.nio.file.Paths; public class InputStreamToFile3 { private static final String FILE_TO = "d:\\test\\test.txt"; public static void main(String[] args) throws IOException { URI u = URI.create("https://www.java265.com/"); try (InputStream inputStream = u.toURL().openStream()) { //Java 1.7 Files.copy(inputStream, Paths.get(FILE_TO)); } } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。