在Java中,读取输入流(比如文件、网络资源等)并将数据输出到本地文件的常见方法是使用java.io包中的类。以下是一个简单的示例,展示了如何将输入流中的数据读取并写入到本地文件中:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
public class StreamCopyExample {
public static void main(String[] args) {
String inputFilePath = "path/to/input/file"; // 输入文件路径
String outputFilePath = "path/to/output/file"; // 输出文件路径
try (InputStream inputStream = new FileInputStream(inputFilePath);
OutputStream outputStream = new FileOutputStream(outputFilePath)) {
byte[] buffer = new byte[1024]; // 缓冲区
int bytesRead;
// 读取输入流并写入输出流
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
System.out.println("File has been copied successfully.");
} catch (IOException e) {
e.printStackTrace();
System.err.println("An error occurred when copying the file.");
}
}
}
在这个示例中,我们使用了FileInputStream来读取输入文件,使用了FileOutputStream来写入输出文件。我们创建了一个缓冲区buffer来存储从输入流中读取的数据,并通过循环不断地读取和写入,直到文件结束。
注意,我们使用了try-with-resources语句来自动关闭流,这是Java 7引入的一个特性,它可以确保在try语句块执行完毕后,自动关闭资源,即使在发生异常的情况下也是如此。
请确保替换inputFilePath和outputFilePath变量的值为实际的文件路径。
如果你的输入流来自其他来源(比如网络资源),你可以使用类似的方法,只是输入流的创建方式会有所不同。例如,如果你从URL读取数据,可以使用URL.openConnection().getInputStream()来获取输入流。
并将数据输出到本地文件&spm=1001.2101.3001.5002&articleId=142461840&d=1&t=3&u=2dea30ca9c514b58ad6abce2d329ebf3)
4845

被折叠的 条评论
为什么被折叠?



