Files can be read using Reader or Stream in java. The Reader is good to use for text data but to work with binary data you should use Stream. FileInputStream
is used to open the stream to read data from file. Here we will convert InputStream to file in Java, we will use OutputStream to write the new file.
可以使用Reader或Java中的Stream读取文件。 Reader适用于文本数据,但要使用二进制数据,应使用Stream。 FileInputStream
用于打开流以从文件读取数据。 在这里,我们将InputStream转换为Java中的文件,我们将使用OutputStream编写新文件。
InputStream到文件 (InputStream to File)
InputStreamToFile.java
InputStreamToFile.java
package com.journaldev.files;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class InputStreamToFile {
public static void main(String[] args) {
try {
InputStream is = new FileInputStream("/Users/pankaj/source.txt");
OutputStream os = new FileOutputStream("/Users/pankaj/new_source.txt");
byte[] buffer = new byte[1024];
int bytesRead;
//read from is to buffer
while((bytesRead = is.read(buffer)) !=-1){
os.write(buffer, 0, bytesRead);
}
is.close();
//flush OutputStream to write any buffered data to file
os.flush();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
That’s all for a simple example to convert InputStream to file in java.
这就是一个简单的示例,将InputStream转换为java中的文件。
翻译自: https://www.journaldev.com/918/java-inputstream-to-file-example