Search code examples
javaarraysprintstream

Using PrintWriter to print an array


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!


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