我将从第三方库获取输入流到我的应用程序.我必须将此输入流写入文件.
以下是我尝试过的代码段:
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);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法来做到这一点?
fge*_*fge 27
既然你坚持使用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();
}
Run Code Online (Sandbox Code Playgroud)
如果你使用Java 7,解决方案就像下面这样简单:
final Path destination = Paths.get("pathToYourFile");
try (
final InputStream in = createInputStreamHere();
) {
Files.copy(in, destination);
}
Run Code Online (Sandbox Code Playgroud)
并且yourInputStream会自动关闭作为"奖金"; Files本来可以处理destination所有.