TL;DR:
I am asking for help considering the structure on the following code, and advice on code structure in general.
The problem in this case is the try blocks, which are messing up the scopes and complicating error handling.
I will elaborate a little for the more patient readers below :icon_cheesygrin:
Hi, I am currently following the programmers challenges from a (somewhat expired) thread on ubuntuforums.org.
I have taught myself whatever little programming I know, and the lack of a teacher is beginning to show, I'm afraid.
I have now come across a problem with the structure of programs, and so I am asking here :icon_cheesygrin:
The following code is supposed to read from one text file and write to another (the text manipulation in between, I haven't gotten around to yet).
I remember having read somewhere that stuff like closing in- and output streams should be done in finally blocks, so that they are executed no matter what.
However, the in and out operations throw some of the same exceptions.
And in order to be able to handle them differently, I thought I'd put them in different try-catch blocks, and then both try-catch blocks in one 'containing' try-catch block.
In the following code the in/out operations are therefore out of scope from where I'm try to close them (in the finally block)
I realise that dropping the outer try-catch block, and putting the instantiation of in and out outside the try block might solve the problem, but then how do I handle errors?
In general I am having trouble figuring out how to structure programs
(especially concerning what to put in separate classes/class files and what to keep in the main class.
So general advice and/or links/names of books to consult will be much appreciated.
Anyway, here is the code so far:
import java.io.*;
import java.util.StringTokenizer;
public class TextMan {
public static void main (String[] args) {
//one try block to rule them all
//(makes sure the streams in the sepparate try blocks are closed, no matter what)
try {
//open input stream.
try {
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream("bhaarat.txt"), "UTF-8"));
} catch (FileNotFoundException e) {
System.out.println("File doesn't exist\n");
in.close();
System.exit(1);
} catch (UnsupportedEncodingException e) {
System.out.println("Your system must support UTF-8 encoding\n");
in.close();
System.exit(1);
} catch (IOException e) {
System.out.println("File found and opened, but couln't read from file");
in.close();
System.exit(1);
}
//open output stream
try {
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("out.txt"), "UTF-8"));
} catch (FileNotFoundException e) {
System.out.println("Could not open output file in current directory");
} catch (UnsupportedEncodingException e) {
System.out.println("Your system must support UTF-8 encoding\n");
}
} finally {
System.out.println("finally");
in.close();
out.close();
System.exit(0);
}
}
}