Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java PrintStream Questions

Tags:

java

io

I am trying to revise a java code to write something into a txt file. The original code is:

try {
    out = new PrintStream(system.out, true, "UTF-8");
} catch (UnsupportedEncodingException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

I use FileOutputStream to do this, and revise the code to:

try {
    FileOutputStream os = new FileOutputStream("wiki.txt", true);
    out = new PrintStream(os, true, "UTF-8");
} catch (UnsupportedEncodingException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

But it doesn't work, the error is:

Wikipedia2Txt.java:56: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
    FileOutputStream os = new FileOutputStream("wiki.txt");
                          ^
1 error

I try two ways: 1, I make a wiki.txt file manually on disk; 2, no wiki.txt exist before run the code. But either doesn't work. It just stopped when compiled.

So what is going on? Thanks.

like image 397
Yuhao Avatar asked Dec 20 '25 11:12

Yuhao


1 Answers

Java is not telling you that the file is not found, just that it may not be found at runtime, and your program is not ready to handle it.

Here is one way to address this:

try {
    FileOutputStream os = new FileOutputStream(file, true);
    out = new PrintStream(os, true, "UTF-8");
} catch (UnsupportedEncodingException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (FileNotFoundException fnf) {
    // TODO Auto-generated catch block
    fnf.printStackTrace();
}

Here is another way:

try {
    FileOutputStream os = new FileOutputStream(file, true);
    out = new PrintStream(os, true, "UTF-8");
} catch (IOException e) {
    // TODO Auto-generated catch block
    fnf.printStackTrace();
}

The first way ensures the compiler that your code is prepared to handle both exceptions separately; the second way ensures the compiler that your code is prepared to handle a superclass of both exceptions. The two ways are not the same, because the second one covers more exceptions that the first one.

Finally, there is an alternative to silence the compiler by declaring your function with a throws block (either a common superclass or the two individual classes would do). This is a way to tell the compiler that your function has no idea of how to handle these exceptions, and that they should be handled by a caller. The consequence of this approach is that every caller of your function must put a try/catch around the call, or declare the exceptions using throws.

like image 187
Sergey Kalinichenko Avatar answered Dec 22 '25 23:12

Sergey Kalinichenko