user1918163
user1918163

Reputation: 15

Having trouble writing to a file

I have a Gui for a stopwatch, it has a Start button, a Stop button, and also a "Split" button, and a Save Splits button. The stopwatch records splits and I would like to be able to write them to a file but I have an error with:

FileWriter splitsWriter= new FileWriter("a.txt");
for(int i=0;i<theSplits.size();i++){
    splitsWriter.write(theSplits.get(i));
}

It says Unhandled exception type IOException but I thought a writer creates the file if it doesn't exist so why should this exception be a problem? I'm just confused..

Upvotes: 1

Views: 57

Answers (1)

Alex
Alex

Reputation: 160

Like pstrjds already said you have to add a try/catch block. Your code should look like this:

try {
    FileWriter splitsWriter= new FileWriter("a.txt");
    for(int i=0;i<theSplits.size();i++){
        splitsWriter.write(theSplits.get(i));
    }
} catch (IOException e) {
    // Do something to handle the exception
}

This should compile.

Upvotes: 1

Related Questions