write to file from stack - java

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()

Related

Nested Try-Catch Block Not Catching Exception

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();

Nested try/catch Blocks: Two Different Implementations

I have been spending sometime relearning Java through a textbook I used in undergrad. At the tail end of their explanation on exceptions, they present the following code:
public class ReadingObjects {
public static void main(String[] args) {
try{
FileInputStream fis = new FileInputStream("objects");
ObjectInputStream ois = new ObjectInputStream(fis);
try{
while(true){
Auto temp = (Auto)ois.readObject();
System.out.println(temp);
}
}
catch(EOFException eofe){
System.out.println("End of file has been reached.");
}
catch(ClassNotFoundException cnfe){
System.out.println(cnfe.getMessage());
}
finally{
System.out.println("Closing file. . .");
ois.close();
}
}
catch(FileNotFoundException fnfe){
System.out.println("Unable to find the objects file.");
}
catch(IOException ioe){
ioe.printStackTrace();
}
}
}
The book's reasoning for using two try/catch blocks is because the program will throw an EOFException no matter what since the ObjectInputStream class has no means to check if there are any more objects in the file (it does not have an equivalent to hasNext() that the Scanner class offers). Also, once an exception is thrown, any code that was written after the point in the try that generated the exception will be ignored; Java will go straight to the catch block for the exception in question. Hence, the inner try/catch block takes care of the EOFException and then jumps into the finally portion. The outer try block takes care of any of the remaining exceptions.
My main question is why use 2 try/catch blocks for this? It seems like it's an overly complicated solution. To be sure I was having the right understanding on this, I went ahead and wrote up the following code which uses only one try/catch block:
public class ReadingObjects {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("objects");
ObjectInputStream ois = new ObjectInputStream(fis);
try{
while(true){
Auto temp = (Auto)ois.readObject();
System.out.println(temp);
}
}
catch(EOFException eofe){
System.out.println("End of file has been reached.");
}
catch(ClassNotFoundException cnfe){
System.out.println(cnfe.getMessage());
}
catch(FileNotFoundException fnfe){
System.out.println("Unable to find the objects file.");
}
catch(IOException ioe){
ioe.printStackTrace();
}
finally{
System.out.println("Closing file. . .");
ois.close();
}
}
}
With the second solution, I still obtain the same output as I did with the first (the book's) solution. Are there any reservations to doing it this way? Should I be wary of adding the throws declaration in my main method?
Any clarification and input on this would be appreciated.
These are two different techniques for handling exception. In first code you are using nested try catch block in sometimes a situation may arise where a part of a block may cause one error and the entire block itself may cause another error. In such cases, exception handlers have to be nested.
in second code you are using try with multiple catch blocks. Both are given as same output but these two are different techniques only for handle the exception.
ois.close() might throw an exception as well. It will be handled gracefully in the first implementation but bubble-up in the second...
The book's explanation doesn't hold water. The EOFException and ClassNotFoundException could just as easily be caught at the outer level. The real difference would be if the ClassNotFoundException was caught inside the while loop, soyou could continue reading other objects you might have the .class file for. However that exception really indicates a deployment problem, and so it may not make much sense to continue reading the stream.

Why does my program stop running and does not return error?

I put the declaration in the while loop, and the program would not running and also does not return any error. I suspect the while loop become an infinite loop.
try
{
while (true)
{
inputStream = new ObjectInputStream (new FileInputStream (fileName));
Ship copyObject = (Ship) inputStream.readObject();
String nameCompany = copyObject.getCompanyName();
if (compName.equalsIgnoreCase(nameCompany)){
listShipName += (copyObject.getShipName() + ", ");
numberOfShip ++;
}
}
}
catch (EOFException e)
{
}
catch (Exception e)
{
e.printStackTrace();
}
But if I put the declaration of input stream out of the while loop, the program runs successfully. Can someone explain why this happens?
try
{
inputStream = new ObjectInputStream (new FileInputStream (fileName));
}
catch (Exception e)
{
e.printStackTrace();
}
try
{
while (true)
{
Ship copyObject = (Ship) inputStream.readObject();
String nameCompany = copyObject.getCompanyName();
if (compName.equalsIgnoreCase(nameCompany)){
listShipName += (copyObject.getShipName() + ", ");
numberOfShip ++;
}
}
}
catch (EOFException e)
{
}
catch (Exception e)
{
e.printStackTrace();
}
You're reopening your file on every iteration through the loop, which means you are only ever reading the first object from the file. But you're reading the same object over and over again.
As well as opening your file only once, you really should try to detect the end of file without throwing an exception. As a matter of style, exceptions should be thrown when things go wrong, not as a matter of course.
Now I realize that in each iteration, I reopen the input stream, so the loop would not reach to the end of the file, and it becomes infinite.

Try-Catch-Finally - Final Block not recognising variable

firstly I know I should be using a try-catch with resources, however I don't currently have the most up to date JDK on my system.
I have the following code below, and am trying to ensure the resource reader is closed using the finally block, however the code below doesn't compile for two reasons. Firstly is that reader may have not been initialized and secondly that close() should be caught within its own try-catch. Dont both of these reasons defeat the object of the initial try-catch block?
I can solve the issue with the finally block close() statement by putting it in its own try-catch. However this still leaves the compile error about reader not being initialized?
I'm presuming I have gone wrong somewhere? Help appreciated!
Cheers,
public Path [] getPaths()
{
// Create and initialise ArrayList for paths to be stored in when read
// from file.
ArrayList<Path> pathList = new ArrayList();
BufferedReader reader;
try
{
// Create new buffered read to read lines from file
reader = Files.newBufferedReader(importPathFile);
String line = null;
int i = 0;
// for each line from the file, add to the array list
while((line = reader.readLine()) != null)
{
pathList.add(0, Paths.get(line));
i++;
}
}
catch(IOException e)
{
System.out.println("exception: " + e.getMessage());
}
finally
{
reader.close();
}
// Move contents from ArrayList into Path [] and return function.
Path pathArray [] = new Path[(pathList.size())];
for(int i = 0; i < pathList.size(); i++)
{
pathArray[i] = Paths.get(pathList.get(i).toString());
}
return pathArray;
}
There is no other way then initialize your buffer and catch the exception. The compiler is always right.
BufferedReader reader = null;
try {
// do stuff
} catch(IOException e) {
// handle
} finally {
if(reader != null) {
try {
reader.close();
} catch(IOException e1) {
// handle or forget about it
}
}
}
The method close will always need a try-catch-block since it declares that it could throw an IOException. It doesn't matter if the call is in a finally block or somewhere else. It just needs to be handled. It is a checked exception.
Read must also be initialized just by null. IMHO this is super useless, but that's Java. That is how it works.
Instead check if reader is null or not and then close it accordingly like below (you should call close() on reader only if it's not null or if it's been already instantiated else you will end up getting null reference exception).
finally
{
if(reader != null)
{
reader.close();
}
}

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