简体   繁体   中英

Java File.toURI() issue on Linux

I'm trying to get the URI of a File to put into a HTML document, which is then later processed to read the image locations (which are in the system temp directory) from that HTML and do some processing on the images.

It works fine on Windows, but on Linux I'm running into issues where the image locations from the HTML can't be found for subsequent processing. I think the issue is as follows...

On Windows, the File.toURI().toString() command is returning (for C:\\temp\\image.jpeg):

file:/C:/temp/image.jpeg

On Linux, it is therefore presumably returning (for /tmp/image.jpeg):

file://tmp/image.jpeg

This is being interpreted by the HTML parser as tmp/image.jpeg (ie a relative path), and therefore can't be found.

Is there an easy workaround for this, or do I need to manually force the URI to be correct (I guess file:///tmp/image.jpeg and file://C:/temp/image.jpeg)?

You can try doing the following:

String imageUri = File.toUri().toString().replaceFirst("^file:/", "");

The regular expression should help you get the file resource on Windows as well as Linux

As I mentioned in my comment to your question: Don't publish file: URIs to HTML documents.

Use relative URIs or absolute URIs with respect to the site's root instead .

Google on the difference of relative and absolute URIs when it comes to publishing web sites for details.

Now, if you are so bent over using file: URIs , then you might want to try to get the canonical path. Hell, the canonical path is the preferred type of path one would want to use to publish file locations (except when publishing on the web as I mentioned before):

// java-like pseudocode:

String myFile = ... // some path, relative or absolute, to a file in an accessible file system

URI = (new File(myFile)).getCanonicalFile().toURI();

Check the Oracle/Sun javadoc information on File and getCanonicalFile/getCanonicalPath for details.

This might still not solve the issue since you are mentioning the HTML parser treats file: URIs as relative (but you do not mention what HTML parser you are using.)

At the end of the day, you will do better with publishing URLs relative to your documents' root instead of using file: URIs. Those URIs were never meant to be used like that.

您要提供绝对路径,需要将图像导入到您的项目中,然后将您项目中的相对路径提供给代码。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM