Home > OS >  While creating a html file in java using file and file writer iam unable to use a title for the html
While creating a html file in java using file and file writer iam unable to use a title for the html

Time:11-03

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

CodePudding user response:

Maybe because there are spaces in your HTML file name. Can you try with Bharatiya_Janta_Party.html or Bharatiya-Janta-Party.html

Please do inform what results did you get.

CodePudding user response:

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 it's 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());
}
  • Related