在Java读取文件的操作中,一定会用到try{}catch(IOException e){}代码块,最后用finally {}块判断IO流是否为Null,不为Null则close。如果一个类中有多个IO流操作方法,那么关闭流的代码块,就会显得臃肿多余。
public static String ReadTxtString(File file) throws IOException {
InputStreamReader inputReader = null;
BufferedReader bufferReader = null;
OutputStream outputStream = null;
String str = null;
try {
InputStream inputStream = new FileInputStream(file);
inputReader = new InputStreamReader(inputStream);
bufferReader = new BufferedReader(inputReader);
// 读取一行
String line = null;
StringBuffer strBuffer = new StringBuffer();
while ((line = bufferReader.readLine()) != null) {
strBuffer.append(line + " ");
}
str = strBuffer.toString();
} catch (IOException e) {
} finally {
if (outputStream != null) {
outputStream.close();
}
if (bufferReader != null) {
bufferReader.close();
}
if (inputReader != null) {
inputReader.close();
}
}
return str;
}
如果一个类中有多个读取操作,那么放眼看去,尽是关闭流的finally块了,所以可以封装一个工具类:
import java.io.Closeable;
import java.io.IOException;
public class IOCloseUtil {
/**
* IO流关闭工具类
*/
public static void close(Closeable... io) {
for (Closeable temp : io) {
try {
if (null != temp)
temp.close();
} catch (IOException e) {
System.out.println("" + e.getMessage());
}
}
}
public static <T extends Closeable> void closeAll(T... io) {
for (Closeable temp : io) {
try {
if (null != temp)
temp.close();
} catch (IOException e) {
System.out.println("" + e.getMessage());
}
}
}
}
finally {
IOCloseUtil.closeAll(outputStream, bufferReader, inputReader);
}