How do I create a new URL
object using a local file, for the purpose of unit tests?
URL url = new URL("http://google.com/pathtoaimage.jpg"); BufferedImage img = ImageIO. read(url); File file = new File("downloaded. jpg"); ImageIO. write(img, "jpg", file);
In your Java program, you can use a String containing this text to create a URL object: URL myURL = new URL("http://example.com/"); The URL object created above represents an absolute URL. An absolute URL contains all of the information necessary to reach the resource in question.
The class named File of the java.io package represents a file or directory (path names) in the system. This class provides various methods to perform various operations on files/directories. In general, an URI (Uniform Resource Identifier) represents a resource.
To get File Uri from a absolute path of File you can use DocumentFile. fromFile(new File(path, name)), it's added in Api 22, and returns null for versions below. Show activity on this post. Uri uri = Uri.
new File(path).toURI().toURL();
Using Java 11:
Path.of(string).toUri();
Using Java 7:
Paths.get(string).toUri();
To convert to the old-school URL class (why?), add .toURL()
. Note there is a difference in the string output. The modern URI::toString
begins with file:///
(the traditional URL syntax) while the nearly-deprecated URL::toString
with file:/
(the modern URI syntax). Weird 🤷
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With