您的位置:首页 > 编程语言 > Java开发

java流关闭改进

2016-10-19 00:00 253 查看
摘要: 简化流关闭时null判断和异常捕捉简化开发

流关闭改进之前:

public void method() {
ByteArrayOutputStream bos = null;
ObjectOutputStream oos = null;
try {
bos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(bos);
.....
} catch (IOException e) {
LogUtil.warn(e);
} finally {
if(bos!=null)
{
try{
bos.flush();
bos.close();
}catch(IOException e){
}
}
if(oos!=null)
{
try{
oos.flush();
oos.close();
}catch(IOException e){
}
}
}
}

改进之后:

public void method() {
ByteArrayOutputStream bos = null;
ObjectOutputStream oos = null;
try {
bos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(bos);
...........
} catch (IOException e) {
LogUtil.warn(e);
} finally {
StreamUtil.flushAndClose(bos, oos);
}
return null;
}

附上代码:

public class StreamUtil {

private static final Logger logger = LoggerFactory.getLogger(StreamUtil.class);

public static void close(InputStream... is) {
if (is != null && is.length > 0) {
for (InputStream inputStream : is) {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
}
}
}
}
}

public static void flushAndClose(OutputStream... os) {
if (os != null && os.length > 0) {
for (OutputStream outputStream : os) {
if (outputStream != null) {
try {
outputStream.flush();
outputStream.close();
} catch (IOException e) {
}
}
}
}
}

public static void flushAndClose(Writer... ws) {
if (ws != null && ws.length > 0) {
for (Writer writer : ws) {
if (writer != null) {
try {
writer.flush();
writer.close();
} catch (IOException e) {
}
}
}
}
}

public static void close(Reader... rs) {
if (rs != null && rs.length > 0) {
for (Reader reader : rs) {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
}
}
}
}
}

public static void close(Connection... cs) {
if (cs != null && cs.length > 0) {
for (Connection c : cs) {
if (c != null) {
try {
c.close();
} catch (SQLException e) {
}
}
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Java