[英]Efficient way to write InputStream to a File in Java 6
I will get input stream from third party library to my application. 我将从第三方库获取输入流到我的应用程序。 I have to write this input stream to a file.
我必须将此输入流写入文件。
Following is the code snippet I tried: 以下是我尝试过的代码段:
private void writeDataToFile(Stub stub) {
OutputStream os = null;
InputStream inputStream = null;
try {
inputStream = stub.getStream();
os = new FileOutputStream("test.txt");
int read = 0;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
os.write(bytes, 0, read);
}
} catch (Exception e) {
log("Error while fetching data", e);
} finally {
if(inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
log("Error while closing input stream", e);
}
}
if(os != null) {
try {
os.close();
} catch (IOException e) {
log("Error while closing output stream", e);
}
}
}
}
Is there any better approach to do this ? 有没有更好的方法来做到这一点?
Since you are stuck with Java 6, do yourself a favour and use Guava and its Closer
: 既然你坚持使用Java 6,请帮自己一个忙,并使用Guava及其
Closer
:
final Closer closer = Closer.create();
final InputStream in;
final OutputStream out;
final byte[] buf = new byte[32768]; // 32k
int bytesRead;
try {
in = closer.register(createInputStreamHere());
out = closer.register(new FileOutputStream(...));
while ((bytesRead = in.read(buf)) != -1)
out.write(buf, 0, bytesRead);
out.flush();
} finally {
closer.close();
}
Had you used Java 7, the solution would have been as simple as: 如果你使用Java 7,解决方案就像下面这样简单:
final Path destination = Paths.get("pathToYourFile");
try (
final InputStream in = createInputStreamHere();
) {
Files.copy(in, destination);
}
And yourInputStream
would have been automatically closed for you as a "bonus"; 并且
yourInputStream
会自动关闭为“奖励”; Files
would have handled destination
all by itself. Files
本身就可以处理destination
。
If you're not on Java 7 and can't use fge's solution, you may want to wrap your OutputStream in a BufferedOutputStream 如果您不使用Java 7且无法使用fge的解决方案,则可能需要将OutputStream包装在BufferedOutputStream中
BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream("xx.txt"));
Such buffered output stream will write bytes in blocks to the file, which is more efficient than writing byte per byte. 这样的缓冲输出流将块中的字节写入文件,这比每字节写入字节更有效。
It can get cleaner with an OutputStreamWriter: 使用OutputStreamWriter可以变得更干净:
OutputStream outputStream = new FileOutputStream("output.txt");
Writer writer = new OutputStreamWriter(outputStream);
writer.write("data");
writer.close();
Instead of writing a string, you can use a Scanner on your inputStream 您可以在inputStream上使用Scanner,而不是编写字符串
Scanner sc = new Scanner(inputStream);
while (sc.HasNext())
//read using scanner methods
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.