I am reading a file and storing its content in a string. The code gives me a warning as : Resource leak : . How do i resolve it?
public static String JsonFileToString(String FileName)
{
String FileContent=null;
try {
FileContent = new Scanner(new File("src/main/resources/" + FileName)).useDelimiter("\\Z").next();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return FileContent;
}
You have to assign the Scanner to a variable, so you can close it in the finally block.
String FileContent=null;
Scanner sc = null;
try {
sc = new Scanner(new File("src/main/resources/" + ""));
FileContent = sc.useDelimiter("\\Z").next();
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
sc.close();
}