Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java URL: Unknown Protocol "C"

Tags:

java

file

url

I know there are similar questions to this one on SO (like this one), however, after reading through the list of "Questions with similar titles", I still feel strongly that this is unique.

I am working with the iText library to generate PDFs from inside a Swing application. iText's Jpeg class requires a URL in its constructor to locate an image/jpg that you want to add to the PDF file.

When I set this URL to the absolute file path of my JPG file, I get a MalformedURLException claiming unknown protocol: c ("c" being the C:\ drive on my local disk).

Is there any hack/circumvention to this, or do I have to host this JPG somewhere and have the URL find it over the net? Here is the code that is failing:

try {
    String imageUrl = "C:\Users\MyUser\image.jpg";
    Jpeg image = new Jpeg(new URL(imageUrl));
} catch(Exception exc) {
    System.out.println(exc.getMessage());
}

Please note: The URL does properly escape the string (thus "\" are converted to "\ \", etc.).

Thanks in advance!

like image 220
IAmYourFaja Avatar asked Dec 12 '11 12:12

IAmYourFaja


3 Answers

You need to turn the path to the image.jpg file into a file:// URL, like this:

String imageUrl = "file:///C:/Users/MyUser/image.jpg";

Otherwise it interprets the C as the URL protocol.

like image 96
Andy Avatar answered Nov 13 '22 11:11

Andy


Try with

String imageUrl = "file:///C:/Users/MyUser/image.jpg";
like image 42
adarshr Avatar answered Nov 13 '22 09:11

adarshr


Try this

try {
    String imageUrl = "file:///C:/Users/MyUser/image.jpg";
    Jpeg image = new Jpeg(new URL(imageUrl));
} catch(Exception exc) {
    System.out.println(exc.getMessage());
}
like image 6
korifey Avatar answered Nov 13 '22 09:11

korifey