Ok this is the code and my question is why do i have to put FileReader inputstream = null; and the same with FileWriter. Why can’t I simply create the objects later in the try block? Am I missing something… I probably am.
public static void main(String[] args) throws IOException{
// TODO Auto-generated method stub
FileReader inputStream = null;
FileWriter outputStream = null;
try {
inputStream = new FileReader("In.txt");
outputStream = new FileWriter("Out.txt");
int c;
while ((c = inputStream.read()) != -1){
outputStream.write(c);
}
}
finally {
if (inputStream != null){
inputStream.close();
}
if (outputStream != null){
outputStream.close();
}
}
Because you won’t be able to refer to them in the
finallyblock, and so you won’t be able to close them.Btw, if they are reader and writer, you’d better name the variables that way, rather than
xStream.I/O handling has always been tedious, that’s why Java 7 introduced “try with resource”