javahtmlfilefilewriter

While creating a html file in java using file and file writer iam unable to use a title for the html file which contains special characters such as?


String Template="<P>sooper</p>
String InputFolder="D:\\project"
String title="name"
FileWriter myWriter = null;
File htmlContent = new File(InputFolder + File.separator +  title+ ".html");
 myWriter = new FileWriter(htmlContent);
myWriter.write(Template);
myWriter.close();

This works fine

but when I replace the title with any string which contains special characters the html file is not being createdb

I was expecting a html file would be created with the name name?.html


Solution

  • You problem is that you try to create a path (under Windows or Linux) with special characters which is not valid for path for your OS. You have to encode the path to the correct one with replasing non ascii symbols to its printable alternative.

    public static void main(String... args) throws IOException {
        String template = "<p>sooper</p>";
        String parent = "d:/project";
        String title = "n   ame";
    
        File file = new File(parent, encode(title + ".html"));
    
        if (!file.exists()) {
            file.getParentFile().mkdirs();
            file.createNewFile();
        }
    
        try (FileWriter out = new FileWriter(file, true)) {
            out.write(template);
        }
    }
    
    private static String encode(String str) throws UnsupportedEncodingException {
        return URLEncoder.encode(str, StandardCharsets.UTF_8.toString());
    }