我注意到当在try {}中使用以下变量时,例如,从最后我不能在它们上使用方法:
import java.io.*; public class Main { public static void main()throws FileNotFoundException { Try{ File src = new File("src.txt"); File des = new File("des.txt"); /*code*/ } finally{ try{ /*closing code*/ System.out.print("After closing files:Size of src.txt:"+src.length()+" Bytes\t"); System.out.println("Size of des.txt:"+des.length()+" Bytes"); } catch (IOException io){ System.out.println("Error while closing Files:"+io.toString()); } } } }
但是,如果将声明放置在Try {}之前的main()中,则程序编译时没有错误,那么有人可以指出解决方案/答案/解决方法吗?
在进入try块之前,需要声明变量,以使它们在方法的其余部分范围内:
try
public static void main() throws FileNotFoundException { File src = null; File des = null; try { src = new File("src.txt"); des = new File("des.txt"); /*code*/ } finally { /*closing code*/ if (src != null) { System.out.print("After closing files:Size of src.txt:" + src.length() + " Bytes\t"); } if (des != null) { System.out.println("Size of des.txt:" + des.length() + " Bytes"); } } }