Java PrintStream Questions - java

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.

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.

The signature of the FileOutputStream constructor that you're using is public FileOutputStream(File file) throws FileNotFoundException. This means it is a checked exception which you have to handle. Therefore make sure that your method in which you have written this code either handles this exception (i.e. specify this exception as part of the catch block) or you specifically throw this exception.
So either of the following would work for you:
Specify in catch block
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 e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Or make your method throw this exception - so your method signature would be something like return_type method_name (params_list) throws FileNotFoundException

You need to handle the situation when the file is not found.
Try this:
try {
File file = (..your code..)
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 e) {
// Handling a situation when file is not found.
e.printStackTrace();
}
Your IDE (for instance Eclipse, IDEA, NetBeans) should provide additional help in such situations. As you have generated stubs, you are probably already using IDE. Isn't your code red-underlined?

You are just trampling upon one of the sore spots of Java: checked exceptions. There's a myriad of exceptions that may happen when your code is running, but only some of them must be declared in advance. My preferred way to handle your piece of code would be to wrap any and all checked exceptions into a RuntimeException that you can handle somewhere else up the stack trace:
try {
FileOutputStream os = new FileOutputStream(file, true);
out = new PrintStream(os, true, "UTF-8");
} catch (RuntimeException e) {
throw e;
}
catch (Exception e) {
throw new RuntimeException(e);
}
In most cases handling exceptions right at the spot where they happen is wrong and leads to swallowed exceptions and generally unreliable, hard-to-debug code.
In a well-engineered application all exceptions that represent a failure—rather than an expected alternative situation—must be propagated up the stack frame towards the so-called exception barrier, where all failures are uniformly handled.

Related

Workaround java.io.EOFException cause by ObjectInputStream [duplicate]

This question already has answers here:
java.io.FileNotFoundException when creating FileInputStream
(2 answers)
Closed 6 years ago.
For my application I want to use a Map to act as a database. To save and load a map, I am writing/reading it to/from database.ser using this 2 methods:
private synchronized void saveDB() {
try {
fileOut = new FileOutputStream(db);
out = new ObjectOutputStream(fileOut);
out.writeObject(accounts);
fileOut.close();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#SuppressWarnings("unchecked")
private void loadDB() {
try {
fileIn = new FileInputStream(db);
in = new ObjectInputStream(fileIn); // that is where error is produced if fileIn is empty
accounts = (Map<String, Client>) in.readObject();
in.close();
fileIn.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I want to load into Map when application starts, so I invoke method in constructor like this:
protected DriveatorImpl() {
accounts = new ConcurrentHashMap<String, Client>();
db = new File("C:/Users/eduar/git/Multy-Threaded-Bank-System/Bank-Services/database.ser");
// also, any suggestions how can I make path to a file more flexible in case I want to run Server side of an app on different machine?
if (!db.exists()) {
try {
db.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
loadDB(); // loads database when server start
}
I am aware of what causing an error, but I don't know what should I change in my design to avoid ObjectInputStream constructor receiving empty stream!
Any suggestions on what I can do differently?
Edit: I want to note that in fresh application run database.ser is empty since there was no entries made into Map yet.
Thank You!
First why the EOFExcpetion occur?
There are no contents in file or file is empty and you tried to read file.
You can avoid the EOFException for an empty file by checking file content length if it is less than or equal to zero means file is empty. another way to check if file is empty
Some code change and it worked for me.
#SuppressWarnings("unchecked")
private void loadDB() {
try {
if (db.length() <= 0) {
// if statement evaluates to true even if file doesn't exists
saveDB(); // save to a file an empty map
// if file doesn't exist, it creates a new one
// call loadDB inside constructor
}
FileInputStream fileIn = new FileInputStream(db);
ObjectInputStream in = new ObjectInputStream(fileIn); // that is where error is produced if fileIn is empty
in.readObject();
in.close();
fileIn.close();
System.out.println(accounts);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Get rid of the file.exists()/file.createNewFile() crap. All it is doing for you is masking the original FileNotFoundException problem, and turning into a thoroughly predictable EOFException because of trying to construct an ObjectInputStream around an empty stream. Handle the original problem. Don't just move it, or turn it into something else.

Difference between catching exceptions using Exception class or FileNotFoundException class

Like i have these two scenarios where we have to handle FileNotFoundException
Case1:
try {
FileInputStream fis = new FileInputStream("test1.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Case2:
try {
FileInputStream fis = new FileInputStream("test1.txt");
} catch (Exception e) {
e.printStackTrace();
}
In both cases printed Stack Trace is same. I would like to know the difference between both implementations and what should be preferred ?
From the docs it gives the reason:
"A subclass inherits all the members (fields, methods, and nested
classes) from its superclass. Constructors are not members, so they
are not inherited by subclasses, but the constructor of the superclass
can be invoked from the subclass."
Exception class is the parent of all the other exception class. So if you know that you are going to get the FileNotFoundException then it is good to use that exception. Making the Exception is a generic call.
This would help you understand:
So as you can see that the Exception class is at a higher hierarchy, so it means it would catch any exception other than the FileIOExcetion. But if you want to make sure that an attempt to open the file denoted by a specified pathname has failed then you have to use the FileIOExcetion.
So here is what an ideal approach should be:
try {
// Lets say you want to open a file from its file name.
} catch (FileNotFoundException e) {
// here you can indicate that the user specified a file which doesn't exist.
// May be you can try to reopen file selection dialog box.
} catch (IOException e) {
// Here you can indicate that the file cannot be opened.
}
while the corresponding:
try {
// Lets say you want to open a file from its file name.
} catch (Exception e) {
// indicate that something was wrong
// display the exception's "reason" string.
}
Also do check this: Is it really that bad to catch a general exception?
In case 2, the catch block will be run for all Exceptions that are caught, irrespective of what exception they are. This allows for handling all exceptions in the same way, such as displaying the same message for all types of exceptions.
In case 1, the catch block will be run for FileNotFoundExceptions only. Catching specific exceptions in different catch blocks allows for the handling of different exceptions in different ways, such as displaying a different message to the user.
When an exception occures the JVM throws the instance of the Exception and that instance is passed to the respective catch block , so in catch(Exception e) e is just the reference variable , but the instance it points to is of Exception thrown .
In case of catch(FileNotFoundException e) , e is also a reference variable and the instance it points to is of Exception thrown , so in both cases different reference varibales (i.e. e) are pointing to the instance of same the Exception (which is thrown) .
this is what i prefer :
try {
// some task
} catch (Exception e) {
if (e instanceof FileNotFoundException) {
// do this
}
if (e instanceof NullPointerException) {
// do this
} else {
// do this
}
}
It is a matter of what you want to intercept. With Exception you will catch any exception but with FileNotFoundException you will catch only that error case, allowing the caller to catch and apply any processing.
When you write this:
try {
FileInputStream fis = new FileInputStream("test1.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
The code inside the catch block is only executed if the exception (thrown inside the try block) is of type FileNotFoundException (or a subtype).
When you write this, on the other hand:
try {
FileInputStream fis = new FileInputStream("test1.txt");
} catch (Exception e) {
e.printStackTrace();
}
the catch block is executed for any exception (since Exception is the root type of any exception).
If your file (test1.txt) does not exist, a FileNotFoundException is thrown and both code snippets are able to catch it.
Try and change it to something like:
try {
FileInputStream fis = new FileInputStream("test1.txt");
} catch (NullPointerException e) {
e.printStackTrace();
}
and you will see that the catch block is no longer executed.
Exception class is the parent of FileNotFoundException.
If you have have provided the Exception in the catch statement, every Exception will be handled in the catch block. But if FileNotFoundException is present in catch block, only exceptions rising due to absence of a File at said source or permissions not available to read the file or any such issues which makes spoils Java's effort to read the file will be handled. All other exceptions will escape and move up the stack.
In the code snippet provided by you, it is fine to use both. But i would recommend FileNotFoundException as it points to exact issue in the code.
For more detail you can read Go Here
Don't use any of those.
Don't catch Exception. Why? Because it also catches all unchecked exceptions (ie, RuntimeExceptions and derivates). Those should be rethrown.
Don't use the old file API. Why? Because its exceptions are unreliable (FileNotFoundException can be thrown if you try and open a file to which you have no read access to for instance).
Use that:
final Path path = Paths.get("test1.txt");
try (
final InputStream in = Files.newInputStream(path);
) {
// do something with "in"
} catch (FileSystemException e) {
// fs level error: no permissions, is a directory etc
} catch (IOException e) {
// I/O error
}
You do need to catch FileSystemException before IOException since the former is a subclass of the latter. Among other possible exceptions you can have: AccessDeniedException, FileSystemLoopException, NoSuchFileException etc.

Why Use FileNotFoundException When Covered by IOException

What is the purpose of catching a FileNotFound and IOException when the FileNotFoundException is covered by IOException?
Examples:
try {
pref.load(new FileInputStream(file.getAbsolutePath()));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
as opposed to:
try {
pref.load(new FileInputStream(file.getAbsolutePath()));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Is it simply to enable different code to be executed if a FileNotFoundException is thrown? Or is there a different reason?
EDIT: What are a few examples of what an IOException could be thrown for? (Besides a FileNotFoundException)
It allows you to specifically handle that case. Perhaps your application needs to do something specific when a file is not found. Such as notify the user that a file was not found, rather then just a generic error.
So basically, yes, it allows different code to be executed specifically when a FileNotFoundException is thrown.
It has to, because you assigning the task for the particular FileNotFound Exception error.
If you do as IOException, user may not get the right information what went wrong in there. so doing in separate way, user come to know exactly what happening in the code.

Saving a singleton object

I know this site isn't made for questions like this but I've been searching for the answer to this I haven't found anything and I need a confirmations.
I have a singleton class which is the centre of my program, in some situations I try to save its state, however it seems it doesn't save properly, and I don't see why because It's not the first time I do this, however It is the first time I try to save a singleton, so is it possible to save a singleton object?
Here are my loading and saving codes of this object
public void Loading(String name) {
ObjectInputStream is = null;
//ignore this variable
game_loaded = 1;
try {
is = new ObjectInputStream(new FileInputStream(name + ".dat"));
//Logica is the singleton class,
//logi is the name of the variable where it is
logi = (Logica) is.readObject();
} catch (FileNotFoundException e1) {
JOptionPane.showOptionDialog(frame, "Game Invalid", "Load",
JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE,
null, new String[] { "Ok" }, "Ok");
return;
} catch (IOException e1) {
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
}
JOptionPane.showOptionDialog(frame, "Game Loaded Sucessfully", "Load",
JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE,
null, new String[] { "Ok" }, "Ok");
}
Save:
public void saving(String nome){
ObjectOutputStream os = null;
try {
os = new ObjectOutputStream(new FileOutputStream(nome+".dat"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
return;
} catch (IOException e) {
// TODO Auto-generated catch block
return;
}
try {
os.writeObject(Logica.getLogica(null));
} catch (IOException e) {
// TODO Auto-generated catch block
return;
}
JOptionPane.showOptionDialog(frame, "Game Saved sucessfully", "Load",
JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE,
null, new String[] { "Ok" }, "Ok");
if (os != null)
try {
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
EDIT
Ok I may have explained corretcly, it doesn't give me any error loading, however it doesn't load the state I saved, it loads an new "Logica" as if I had created a new one
There's nothing about Singleton per se that says it can't be serialized; you can write incorrect serialization code for any class. It's not clear what's wrong, and I'm not willing to pore over your code to figure it out, but it should be possible to do.
You have an empty catch block for IOException. That's always a bad idea. You've swallowed the exception that might explain everything. Print the stack trace.
The situation you have described is not possible. Ergo you haven't described it correctly. Probably there is something wrong with your observations.
I strongly suspect an IOException or FileNotFoundException, despite your comment in another answer. You have posted code that ignores exceptions in at least four separate places. The presumption is overwhelming.
In fact your exception handling needs a lot of work. You aren't closing the file in case of exceptions for example. There are no finally blocks. You have multiple try/catch blocks where you should have one try and several catches.
Further questions along other lines of enquiry. Is the file being created? With non-zero length? Or else maybe the singleton class only has transient fields?

Handling IO exceptions in Java

Basically, I want to open a file, read some bytes, and then close the file. This is what I came up with:
try
{
InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
try
{
// ...
inputStream.read(buffer);
// ...
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
try
{
inputStream.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
Maybe I'm spoiled by RAII, but there must be a better way to do this in Java, right?
If you have the same exception handling code for IOException and FileNotFoundException then you can rewrite your example in a more compact way with only one catch clause:
try {
InputStream input = new BufferedInputStream(new FileInputStream(file));
try {
// ...
input.read(buffer);
// ...
}
finally {
input.close();
}
}
catch (IOException e) {
e.printStackTrace();
}
You can even get rid of the outer try-catch if you can propagate the exception which probably makes more sense then manually printing the stack trace. If you don't catch some exception in your program you'll get stack trace printed for you automatically.
Also the need to manually close the stream will be addressed in Java 7 with automatic resource management.
With automatic resource management and exception propagation the code reduces to the following:
try (InputStream input = new BufferedInputStream(new FileInputStream(file))) {
// ...
input.read(buffer);
// ...
}
Usually these methods are wrapped up in libraries. Unless you want to write at this level, it is best to create your own helper methods or use existing ones like FileUtils.
String fileAsString = Fileutils.readFileToString(filename);
// OR
for(String line: FileUtils.readLines(filename)) {
// do something with each line.
}
I don't know if it is the right way, but you can have all your code in the same try block, and then have the different catch blocks right after each other.
try {
...
}
catch (SomeException e) {
...
}
catch (OtherException e) {
...
}
If you want to do this in plain Java, the code you have posted looks OK.
You could use 3rd party libraries such as Commons IO, in which you would need to write much less code. e.g.
Check out Commons IO at:
http://commons.apache.org/io/description.html
Sometimes you can reduce the code to the following:
public void foo(String name) throws IOException {
InputStream in = null;
try {
in = new FileInputStream(name);
in.read();
// whatever
} finally {
if(in != null) {
in.close();
}
}
}
Of course this means the caller of foo has to handle the IOException but this should be the case most of the time anyway. In the end you don't really reduce all that much complexity but the code becomes much more readable due to less nested exception handlers.
My take on this without using utilities would be:
InputStream inputStream = null;
try {
inputStream = new BufferedInputStream(new FileInputStream(file));
// ...
inputStream.read(buffer);
// ...
} catch (IOException e) {
e.printStackTrace();
throw e; // Rethrow if you cannot handle the exception
} finally {
if (inputStream != null) {
inputStream.close();
}
}
Not a one-liner, but not pretty bad. Using, say, Apache Commons IO it would be:
//...
buffer = FileUtils.readFileToByteArray(file);
//...
The thing to rembember is that standard Java lacks many of these little utilities and easy to use interfaces that everyone needs, so you have to rely on some support libraries like Apache Commons, Google Guava, ... in your projects, (or implement your own utility classes).
Use org.apache.commons.io.FileUtils.readFileToByteArray(File) or something similar from that package. It still throws IOException but it deals with cleaning up for you.
Try the following:
try
{
InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
byte[] buffer = new byte[1024];
try
{
// ...
int bytesRead = 0;
while ((bytesRead = inputStream.read(buffer)) != -1) {
//Process the chunk of bytes read
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
inputStream.close();
}
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
Google guava has tried to address this problem by introducing Closeables.
Otherwise you have to wait until AutoCloseable from JDK 7 comes out as it addresses some of the cases when IOException is thrown.

Categories