Nested Try-Catch Block Not Catching Exception - java

My program is attempting to scan through my directory in search of the existence of .cmp or .txt files.
If fileName were to equal "test" and if neither test.cmp nor test.txt files existed, my program would still throw a FileNotFoundException despite my try-catch block under the first catch. I've tried moving the second try-catch block around, but nothing seems to work – everything I test the code out with a file that doesn't exist still ends up throwing an exception.
public int checkFileExistence() {
BufferedReader br = null;
int whichFileExists = 0;
try {//check to see if a .cmp exists
br = new BufferedReader(new FileReader(fileName + ".cmp"));
whichFileExists = 0;// a .cmp exists
}
catch (IOException e){ //runs if a .cmp file has not been found
try {//check to see if a .txt file exists
br = new BufferedReader(new FileReader(fileName + ".txt"));
whichFileExists = 1;//a .txt file exists
}
catch (IOException e2) {//if no .txt (and .cmp) file was found
e2.printStackTrace();
whichFileExists = 2; //no file exists
}
}
finally {
try {
br.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return whichFileExists;
}
I would expect the program to work, but each time I test the program, the program throws a FileNotFoundException where it says "test.txt" doesn't exist.

It is printing that exception because of this line:
e2.printStackTrace();
It's working as you are expecting, just printing the error it got. You can remove these printStackTrace() calls if you don't want to see them. Well, don't remove the one in the last catch block, otherwise you would never know if there is a problem there.
On a separate note, this design is totally based on exceptions, which is not recommended. I'm sure there are methods in the File class to check for existence of files.

This program is working as expected...
catch (IOException e2) {//if no .txt (and .cmp) file was found
e2.printStackTrace();
whichFileExists = 2; //no file exists
}
Above catch clause catches your IOException and prints it with e2.printStackTrace();

Related

File isn't saved correctly

I am making a save/load feature for the settings in my application. Upon launching the program, it tries to find the file. If it fails, it tries to create a file with default settings (code below)
try (FileWriter fileWriter = new FileWriter(absolutePath))
{
fileWriter.write("theme=light\n");
fileWriter.write("resolution=1280x720\n");
fileWriter.write("printfps=false\n");
System.out.println("Reset settings");
load();
}
catch (FileNotFoundException e)
{
System.out.println("Settings File not found.");
}
catch (IOException e)
{
e.printStackTrace();
}
After it has written this, it goes on to load the file. (calling load() method)
In the load method, the application reads the contents of the file (code below).
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(absolutePath)))
{
String line = bufferedReader.readLine();
System.out.println(line);
while(line != null)
{
if (line.contains("="))
{
String key = line;
String value = line;
while (key.contains("="))
{
key = key.substring(0, key.length() - 1);
}
while (value.contains("="))
{
value = value.substring(1);
}
settings.put(key, value);
}
System.out.println(line);
line = bufferedReader.readLine();
}
System.out.println(settings);
}
However, it returns that the file is empty. After messing with breakpoints, I can confirm that the file is indeed not updated at that point. The rather weird thing is that if I pause the application at a later time, the file seems to contain the text that was written to it, even though the file is not touched later in the program.
This makes me believe that it takes some time for the file to update, thus not updating in time for the load() method. Is this correct, or am I missing something? And is there a workaround?
All help is appreciated :)
You're calling load() before you actually saved the file.
To save the file, call fileWriter.close() or just move the load() call out of the try-with-resource block with the FileWriter:
try (FileWriter fileWriter = new FileWriter(absolutePath))
{
fileWriter.write("theme=light\n");
fileWriter.write("resolution=1280x720\n");
fileWriter.write("printfps=false\n");
}
catch (FileNotFoundException e)
{
System.out.println("Settings File not found.");
}
catch (IOException e)
{
e.printStackTrace();
}
// FileWriter closed now and the file contents saved
System.out.println("Reset settings");
load();

How can I increment a number in a file by an amount?

I have got a .txt file which stores a players' money. I need this file to increment or detriment a certain amount depending on if the player kills something or if they buy something from the shop.
The issue is that I do not know how to actually increment or detriment the contents. I can delete/recreate the .txt file with the new money, however because multiple threads will be accessing the file, then there is the risk that the file may not exist due to it being deleted and not regenerated yet.
Just to clarify, there will only be one thread at a time modifying the file. Other threads will only be reading the file.
So how would I do this without deleting the data/file first?
Here is the code ,read file first and then increment it and store again -
BufferedWriter out = null;
try {
// Read File Contents - score
BufferedReader br = new BufferedReader(new FileReader("c:\\a.txt"));
String storedScore="0";
int storedScoreNumber = 0;
while ((storedScore = br.readLine()) != null) {
storedScoreNumber=(Integer.parseInt(storedScore==null?"0":storedScore));
}
// Write File Contents - incremented socre
out = new BufferedWriter(new FileWriter("c:\\a.txt", false));
out.write(String.valueOf(storedScoreNumber+1));
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Have a singleton data accessor with a queue so that it is the only one manipulating the file. If necessary acknowledge to client threads after the write.

write to file from stack

folks. I'm trying to write to a file from a stack. The stack was created by reading from another file. I'm using the stack so that I can reverse the file I read in. The file names to read and write to are from the command line.
This is how I have my stack implemented:
while(read.hasNext()) {
stack.push(read.next());}
The code for my other file that the stack is supposed to write to:
FileWriter w = null;
try {
w = new FileWriter(new File(args[1]));
} catch (IOException e) {
e.printStackTrace();
}
if (!stack.isEmpty()) { //this was a while statement
try {
w.write(stack.pop());
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("Didn't make it.");
}
The problem that I'm having is when I run my program, the file I want to write to is created, but nothing gets written to the file. I originally thought that my stack didn't have anything in it (that's why I changed my while statement to an if; it's temporary). The "Didn't make it." didn't print so I now know it's not that. What am I doing wrong here? Any help is appreciated.
After w.write(stack.pop()); call the fush() method:
w.write(stack.pop());
w.flush();
and you can return the while statement. At the end call w.close();
the method stack.pop returns an Object if you do not specify at the time of declaration like this
Stack<String> stack = new Stack<String>();
and after writing you should use w.flush() and also you should use the w.close.
you should nest the while statement itself into the try block
for instance
try {
while(!stack.isEmpty()) {
w.write(stack.pop()); // assuming you have declared it as Stack<E>
}
w.flush();
w.close();
} catch(IOException e) {
e.printStackTrace();
}
EDIT:
after you are done with FileWriter when you close it, that has to nested inside a try catch block to catch any IOException if thrown. if you use the w.write() method inside the try catch block that is within the while loop then after the while loop iteration is over you have to build another try catch to place w.close()

File can not be executed from Java

When i try this code, it seems as executed but it is not executed.
The process builder can find the executable file. System writes the println commands.
I found some example codes but my executable file is not in same folder with java file.
private static void executeOneFile(String folderPath) {
Process p;
String exePath = path + "\\" + folderPath + "\\";
try {
p = new ProcessBuilder(exePath + "myFile.exe").start();
//p = Runtime.getRuntime().exec("myFile.exe", null , new File(exePath) );
System.out.println("p is running");
p.waitFor();
System.out.println("p ended");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
There are several problems with the code above:
You don't handle stdin/stdout properly. So maybe there is an error but you won't see it because you're not reading the output of the child process.
Next, it's always a good idea to close the child's stdin with p.getOutputStream().close() to make sure it doesn't hang waiting for input.
Lastly, the current directory of the process is the same as that of the Java VM. So if you use relative paths to write the file, it will end up somewhere but rarely where you expect. Pass the absolute path of the file to your child process to make sure the output goes where it should.

Java File Handling, what did I do wrong?

Wrote up a basic file handler for a Java Homework assignment, and when I got the assignment back I had some notes about failing to catch a few instances:
Buffer from file could have been null.
File was not found
File stream wasn't closed
Here is the block of code that is used for opening a file:
/**
* Create a Filestream, Buffer, and a String to store the Buffer.
*/
FileInputStream fin = null;
BufferedReader buffRead = null;
String loadedString = null;
/** Try to open the file from user input */
try
{
fin = new FileInputStream(programPath + fileToParse);
buffRead = new BufferedReader(new InputStreamReader(fin));
loadedString = buffRead.readLine();
fin.close();
}
/** Catch the error if we can't open the file */
catch(IOException e)
{
System.err.println("CRITICAL: Unable to open text file!");
System.err.println("Exiting!");
System.exit(-1);
}
The one comment I had from him was that fin.close(); needed to be in a finally block, which I did not have at all. But I thought that the way I have created the try/catch it would have prevented an issue with the file not opening.
Let me be clear on a few things: This is not for a current assignment (not trying to get someone to do my own work), I have already created my project and have been graded on it. I did not fully understand my Professor's reasoning myself. Finally, I do not have a lot of Java experience, so I was a little confused why my catch wasn't good enough.
Buffer from file could have been null.
The file may be empty. That is, end-of-file is reach upon opening the file. loadedString = buffRead.readLine() would then have returned null.
Perhaps you should have fixed this by adding something like if (loadedString == null) loadedString = "";
File was not found
As explained in the documentation of the constructor of FileInputStream(String) it may throw a FileNotFoundException. You do catch this in your IOException clause (since FileNotFoundException is an IOException), so it's fine, but you could perhaps have done:
} catch (FileNotFoundException fnfe) {
System.err.println("File not fonud!");
} catch (IOException ioex {
System.err.println("Some other error");
}
File stream wasn't closed
You do call fin.close() which in normal circumstances closes the file stream. Perhaps he means that it's not always closed. The readLine could potentially throw an IOException in which case the close() is skipped. That's the reason for having it in a finally clause (which makes sure it gets called no matter what happens in the try-block. (*)
(*) As #mmyers correctly points out, putting the close() in a finally block will actually not be sufficient since you call System.exit(-1) in the catch-block. If that really is the desired behavior, you could set an error flag in the catch-clause, and exit after the finally-clause if this flag is set.
But what if your program threw an exception on the second or third line of your try block?
buffRead = new BufferedReader(new InputStreamReader(fin));
loadedString = buffRead.readLine();
By this point, a filehandle has been opened and assigned to fin. You could trap the exception but the filehandle would remain open.
You'll want to move the fin.close() statement to a finally block:
} finally {
try {
if (fin != null) {
fin.close();
}
} catch (IOException e2) {
}
}
Say buffRead.readLine() throws an exception, will your FileInputStream ever be closed, or will that line be skipped? The purpose of a finally block is that even in exceptional circumastances, the code in the finally block will execute.
There are a lot of other errors which may happen other than opening the file.
In the end you may end up with a fin which is defined or not which you have to protect against null pointer errors, and do not forget that closing the file can throw a new exception.
My advice is to capture this in a separate routine and let the IOExceptions fly out of it :
something like
private String readFile() throws IOException {
String s;
try {
fin = new FileInputStream(programPath + fileToParse);
buffRead = new BufferedReader(new InputStreamReader(fin));
s = buffRead.readLine();
fin.close();
} finally {
if (fin != null {
fin.close()
}
}
return s
}
and then where you need it :
try {
loadedString = readFile();
} catch (IOException e) {
// handle issue gracefully
}

Categories