Question

I have an array named theDirectory, which holds many DirectoryEntrys, each consisting of a name and telno. I now need to print each DirectoryEntry inside theDirectory into a text file. This is the method I have tried, however i am getting the error: unreported exception IOException; must be caught or declared to be thrown.

My code:

public void save() {
    PrintWriter pw = new PrintWriter(new FileWriter("directory.txt", true)); 

    for (DirectoryEntry x : theDirectory) {
        pw.write(x.getName());
        pw.write(x.getNumber());
        pw.close();
    }
}

any help on this matter would be much appreciated!

Was it helpful?

Solution

your modified code should look like this :

  public void save() {

PrintWriter pw=null;
    try{
        pw = new PrintWriter(new FileWriter("directory.txt", true)); 

        for (DirectoryEntry x : theDirectory) {
            pw.write(x.getName());
            pw.write(x.getNumber());

        }

    }
    catch(IOException e)
    {
     e.printStackTrace();
    }

finally
{
   pw.close();
}

    }

as mentioned by Jon Skeet

OTHER TIPS

The other answers here have some flaws, this is probably what you want if you're using Java 7 or later:

public void save() {
    try (PrintWriter pw = new PrintWriter(new FileWriter("directory.txt", true))) {         
        for (DirectoryEntry x : theDirectory) {
            pw.write(x.getName());
            pw.write(x.getNumber());                
        }
    }
    catch (IOException ex)
    {
        // handle the exception
    }   
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top