Java 文件关闭的位置

public class InputFile {
	private BufferedReader in;
	
	public InputFile(String fname) throws Exception {
		try {
			in = new BufferedReader(new FileReader(fname));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			throw e;
		} catch (Exception e) {
			try {
				in.close();
			} catch (IOException e2) {
				e2.printStackTrace();
			}
		} finally {
			// 不能在这里关闭
		}
	}
	
	public String getLine() {
		String s;
		try {
			s = in.readLine();
		} catch (IOException e) {
			throw new RuntimeException("readLine failed");
		}
		return s;
	}
	
	public void dispose() {
		try {
			in.close();
			System.out.println("dispose() successful");
		} catch (IOException e) {
			throw new RuntimeException("in.close() failed");
		}
	}
	
	public static void main(String[] args) {

	}

}
 

public class CleanUp {

	public static void main(String[] args) {
		try {
			// 外层的捕获是未能打开文件 内存的finally 是确定文件已经打开了
			// 出现异常就需要关闭
			InputFile inputFile  = new InputFile("test.java");
			try {
				String s;
				int i = 1;
				while ((s = inputFile.getLine()) != null) {
					System.out.println(s);
				}
			} catch (Exception e) {
				System.out.println("Caught Exception in main");
				e.printStackTrace(System.out);
			} finally {
				inputFile.dispose();
			}
		} catch (Exception e) {
			System.out.println("InputFile construction failed");
		}
	}

}

你可能感兴趣的:(java)