JIYIK CN >

Current Location:Home > Learning > PROGRAM > Java >

Get resource URL and content in Java

Author:JIYIK Last Updated:2025/04/14 Views:

getResource()This tutorial will demonstrate how to use the function to get the resource URL and read the resource file in Java .


getResource()Use the function to get the resource URL in Java

We will use the method in Java getResource()to obtain the URLs of three files: image.png, image1.png, resourcetext.txt.

We will getResource()pass the resource URL as a string in the body of the function. The function then searches for the given resource string and returns an object containing the URL.

grammar:

getResource(String);
public resource = yourclassname.getResource("Resource URL");

Sample code:

/*//you will learn how to get image URL in the following program
//import statements
 */
import java.lang.*;
import java.net.URL;
public class getImageUrl {
  public static void main(String[] args) throws Exception {
    getImageUrl obj = new getImageUrl();
    @SuppressWarnings("rawtypes") Class resource = obj.getClass();
    URL imageurl = resource.getResource("/image.png");
    System.out.println("Resource URL one is = " + imageurl);
    URL imageurl2 = resource.getResource("/image2.png");
    System.out.println("Resource URL two is = " + imageurl2);
    URL texturl = resource.getResource("/textresource.txt");
    System.out.println("Resource URL of the text file  is = " + texturl);
  }
}

Output:

Resource URL one is = file:/C:/Users/NAME/Desktop/JAVA/get%20resource%20url%20java/bin/image.png
Resource URL two is = file:/C:/Users/NAME/Desktop/JAVA/get%20resource%20url%20java/bin/image2.png
Resource URL of the text file is = file:/C:/Users/NAME/Desktop/JAVA/get%20resource%20url%20java/bin/textresource.txt

As we can see, we store the three files in the string URL. Then we use obj.getClass()the method to get the main class that receives the image URL.

getResource()function is a function that returns a URL.


getResourceAsStream()Get resource content using in Java

Java reserves a getResourceAsStream()method called to read files. This function returns a InputStreamobject containing the specified resource of the class.

For the following examples, we will use getResourceAsStream()to read this file: /get resource URL java/src/readfile/GetResourceReadFile.java. There is also the string getresourcefromhere = "readfile/example.json";where we store the JSON file.

grammar:

private InputStream getFileFromResourceAsStream(String getresourcefromhere) {
  ClassLoader cL = getClass().getClassLoader();
  InputStream inputStream = cL.getResourceAsStream(getresourcefromhere);
  return inputStream;
}

If you understand the basic syntax, check out the complete program below.

The program is available for every platform. You should pay attention to the main class and file directory management.

// import necessary packages
package readfile;
import java.io.*;
import java.nio.charset.StandardCharsets;
// start function
public class GetResourceReadFile {
  private static final String String = null;
  public static void main(String[] args) throws IOException, Exception {
    GetResourceReadFile app = new GetResourceReadFile();
    // get resource file
    String getresourcefromhere = "readfile/example.json";
    // use inputStream to return object containing resource
    InputStream getresourceandreadit = app.getFileFromResourceAsStream(getresourcefromhere);
    printInputStream(getresourceandreadit);
  }
  private InputStream getFileFromResourceAsStream(String getresourcefromhere) {
    // load class
    ClassLoader cL = getClass().getClassLoader();
    InputStream inputStream = cL.getResourceAsStream(getresourcefromhere);
    return inputStream;
  }
  private static void printInputStream(InputStream r) {
    try (InputStreamReader sR = new InputStreamReader(r, StandardCharsets.UTF_8);
         BufferedReader R = new BufferedReader(sR)) {
      String GOT_IT = String;
      // not necessary but will give you basic idea
      if (GOT_IT == String) {
        // you can print multiple files
        while ((GOT_IT = R.readLine()) != null) {
          // print file
          System.out.println(GOT_IT);
        }
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

Output:

{
    "File Name": "Demonstration File",
    "File Type": "JSON FILE",
    "File Reader": "getResource",
    "File creation date:": 2/18/2022,
    "Platform": {
        "Langauge Type": "Programming",
        "Langugae Name": "JAVA",
        "Platform": "Oracle",
        "Importance": "Very High"
    },
    "Development Environment": [
        { "JDK": "JAVA", "LATEST": "17" }
    ]
}

The entire program is the same as the previous example with the URL . The only differences are InputStreamand ClassLoader cL = getClass().getClassLoader();.

Previous:Getting the host name in Java

Next: None

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Getting the host name in Java

Publish Date:2025/04/14 Views:78 Category:Java

In this tutorial, we will see how to get the IP address and host name using Java API. InetAddress Get the host name in Java using The package java.net contains classes for handling the IP address and host name of the current machine InetAdd

Get the IP address of the current device in Java

Publish Date:2025/04/14 Views:53 Category:Java

An Internet Protocol (IP) address is an identifier for each device connected to a TCP/IP network. This identifier is used to identify and locate nodes in the middle of communication. The IP address format, such as 127.0.0.0, is a human-read

Generate a random double value between 0 and 1 in Java

Publish Date:2025/04/14 Views:153 Category:Java

This article will introduce three methods to generate double random values ​​between 0 and 1 of primitive types. To demonstrate the randomness of the generated values, we will use a loop to generate ten random double values ​​betwee

Setting the seed of a random generator in Java

Publish Date:2025/04/14 Views:62 Category:Java

A seed is a number or vector assigned to a pseudo-random generator to generate the desired sequence of random values. If we pass the same seed, it will generate the same sequence. We usually assign the seed as the system time. In this way,

Switching on enumeration types in Java

Publish Date:2025/04/14 Views:96 Category:Java

This article explains how to use enum in Java . We will use statement switch with enum in two ways . switch In Java, we use traditional switch and case to perform enumeration operations. switch In this example, we SwitchEnum create an enume

How to delay for a few seconds in Java

Publish Date:2025/04/14 Views:131 Category:Java

This tutorial explains how to create program delays in Java and gives some sample code to understand it. There are several ways to create a time delay, such as TimeUnit.sleep() ,, ScheduleAtFixedRate() etc. Thread.sleep() Let's look at an e

How to Convert Hashmap to JSON Object in Java

Publish Date:2025/04/14 Views:112 Category:Java

This article explains how to convert a Hashmap to a JSON object in Java. We will see a detailed example of creating a hashmap and then converting it to a JSON object. Hashmap and JSON are both very commonly used by developers as they help u

How to sort a Map by value in Java

Publish Date:2025/04/14 Views:171 Category:Java

This tutorial explains how to Mapkey, value sort pairs by value in Java and lists some sample codes to understand it. There are several ways to Map sort . Here we use sort() the , sorted() method, and Comparator interface. Let's look at an

How to Print a HashMap in Java

Publish Date:2025/04/14 Views:85 Category:Java

This tutorial explains how to print HashMap an element in Java and also provides some sample code to understand the topic. HashMap It is Map an implementation class of the interface and is used to collect elements into key and value pairs.

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial