When I compile the below code, it shows error "cannot find symbol variable out" But if i comment the code in the finally block, I am able to compile successfully.
Please advise.
public static int writeFile (String p_file_path, String p_data) throws Exception
{
try {
FileWriter outFile = new FileWriter(p_file_path,true);
PrintWriter out = new PrintWriter(outFile);
out.println(p_data);
} catch (Exception e) {
} finally {
out.close();
}
return SUCCESS;
}
You need to define "out" outside try-block if you want to reference it in the finally block, something like
PrintWriter out = null;
try
{
FileWriter outFile = new FileWriter(p_file_path,true);
out = new PrintWriter(outFile);
out.println(p_data);
}
finally
{
if (out != null)
out.close();
}
You declare out
within the try
block. This means that is out of scope as soon as you leave the try
portion of your try-finally
statement. You can either declare it outside of your try
statement and do a null check in your finally
block, or use Java 7's try-with-resources
statement.
PrintWriter out;
try {
out = ...
} finally {
if(out != null) {
out.close();
}
}
or
try(PrintWriter out = ...) {
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.