java-在不同位置关闭FileOutputStream的最佳编码实践
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java-在不同位置关闭FileOutputStream的最佳编码实践,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1643字,纯文字阅读大概需要3分钟。
内容图文
![java-在不同位置关闭FileOutputStream的最佳编码实践](/upload/InfoBanner/zyjiaocheng/669/39c9ba2cf11743b2a54c6eb6efe82cc5.jpg)
properties.storeToXML(new FileOutputStream(new File(m_wcontext.getProject().getBaseDirectory() +
"/" + m_wcontext.getServiceName() + ".properties")),null);
我在10个不同的地方都有类似的方法调用.在代码审查期间,建议我需要关闭资源.推荐的方法是使用如下所示的修改代码:但这会使代码变得笨拙,因为我需要将代码重复10次.
try {
fios = new FileOutputStream(new File(m_wcontext.getProject().getBaseDirectory() +
"/" + m_wcontext.getServiceName() + ".properties"));
properties.storeToXML(fios, null);
} finally {
if(fios!=null) {
fios.close();
}
}
请问下面的方法很好.有更好的吗?
FileOutputStream fios = getFileOutPutStream(m_wcontext.getProject().getBaseDirectory() + "/" + m_wcontext.getServiceName() + ".properties");
properties.storeToXML(fios, null);
// ...
private FileOutputStream getFileOutPutStream(String path) throws IOException {
FileOutputStream fios=null;
try {
fios = new FileOutputStream(new File(m_wcontext.getProject().getBaseDirectory() +
"/" + m_wcontext.getServiceName() + ".properties"));
properties.storeToXML(fios, null);
} finally {
if(fios!=null) {
fios.close();
}
}
return fios;
}
解决方法:
假设您使用Java 7或更高版本进行编译,则可以使用try-with-resources语句自动关闭资源:
private void writeXML(String path) throws IOException {
try (FileOutputStream fios = new FileOutputStream(new File(path))) {
properties.storeToXML(fios, null);
}
}
我已经使该方法无效,因为在将它作为参数传递给storeToXML之后,看起来您不需要FileOutputStream.
要调用此方法,可以使用以下方法:
String path = m_wcontext.getProject().getBaseDirectory() +
File.separator + m_wcontext.getServiceName() + ".properties";
try {
writeXML(path);
} catch (IOException e) {
e.printStackTrace();
}
内容总结
以上是互联网集市为您收集整理的java-在不同位置关闭FileOutputStream的最佳编码实践全部内容,希望文章能够帮你解决java-在不同位置关闭FileOutputStream的最佳编码实践所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。