Search code examples
javafileurlexceptionmalformed

Java - Malformed URL - Not correct - No protocol


This code:

        String file = "";
    String filename = "";
    try{
        BufferedReader ins = new BufferedReader(new FileReader(new File("filename.txt")));//get file name
        while (ins.ready()) {
           filename = ins.readLine();
        }
        ins.close();
        }catch(Exception e){
        }

        String[] sa = filename.split("/");
        file = sa[sa.length - 1];

        try {
            System.out.println(filename);
        } catch (Exception e) {
            e.printStackTrace();
        }

Prints:

http://wordpress.org/plugins/about/readme.txt

When I try to do :

         URL url = new URL(filename);

I get the malformed URL exception : no protocol This is happening for no reason. If I manually assign the filename string to "http://wordpress.org/plugins/about/readme.txt" it will work perfectly , is there something wrong with the file reader?

The thing goes like

Read a string from the file and then make it a URL! Stop editing wrongly!


Solution

  • An idea:

    It could be that the file is saved in UTF-8, but with an extra BOM character at the file beginning. This is a zero-width Unicode space.

    filename = filename.replaceFirst("^\uFFFE", "");