-4

I've started to learn Java and working with files is a little bit hard for me. Can you check my code and see what's going wrong?

public class Arena  {
FileWriter f = createFile();
protected void print(String me){
        try {
            f.write(me);
            System.out.println(me);
        } catch (IOException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }

    }
    protected FileWriter createFile() {
        try {
            return new FileWriter("src/battle.txt");
        } catch (IOException e) {
            System.out.println("An error occurred.");
            System.exit(1);
            return null;
        }
    }

And this method print I use as System.out.println But when I run my code my file battle.txt is empty. How I can fix it?

1 Answers1

4

You need to close() your FileWriter. Currently, you open it at the class level and never close it. I would use a try-with-Resources and something like

protected void print(String me) {
    try (FileWriter f = createFile()) {
        f.write(me);
        System.out.println(me);
    } catch (IOException e) {
        System.out.println("An error occurred.");
        e.printStackTrace();
    }
}

Which should resolve your issue.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249