Search code examples
javahtmlfilefilewriterbufferedwriter

Cannot write to created HTML file in Java


Here is my code:

public static void create() {
        String path = FileSystemView.getFileSystemView().getHomeDirectory().getAbsolutePath() + "\\JWPLfile";
        int index = 0;
        while (true) {
            try {
                File f = new File(path + index + ".html");
                BufferedWriter bw = new BufferedWriter(new FileWriter(f));
                bw.write(fileContent);
                break;
            } catch (Exception e) {
                index++;
            }
        }
    }

But the newly created HTML file is empty although fileContent is not.


Solution

  • You need to ensure the file is closed. Use try-with-resources as in:

            File f = new File(path + index + ".html");
            try (FileWriter fw = new FileWriter(f)) {
                BufferedWriter bw = new BufferedWriter(fw);
                bw.write(fileContent);
                break;
            } catch (Exception e) {
                index++;
            }
    

    Note that the (essentially) empty catch block will hide any exceptions from you. Not a good idea.

    Also, while(true) and break are unnecessary.