Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a local file in to URL in Java

Tags:

java

url

junit

How do I create a new URL object using a local file, for the purpose of unit tests?

like image 349
MeanwhileInHell Avatar asked Oct 11 '22 14:10

MeanwhileInHell


People also ask

How do you create a URL for a file?

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

How do you give a URL in Java?

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.

What is Java URI file?

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.

How do I find the URI of a file?

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.


2 Answers

new File(path).toURI().toURL();
like image 320
jarnbjo Avatar answered Oct 22 '22 10:10

jarnbjo


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 🤷

like image 53
Aleksandr Dubinsky Avatar answered Oct 22 '22 12:10

Aleksandr Dubinsky