Java URL: Unknown Protocol “C”

回眸只為那壹抹淺笑 提交于 2020-04-08 19:01:44

问题


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!


回答1:


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.




回答2:


Try with

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



回答3:


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());
}



回答4:


Searching the file with its directory and adding in the image to assign to the ImageView

File file = new File("F:/a.jpg");
Image image = new Image(arquivo.toURI().toString()); //here is magic happens
imageView.setImage(image);


来源:https://stackoverflow.com/questions/8474694/java-url-unknown-protocol-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!