Leggere file da resources in Java con Google Guava

Mattepuffo's logo
Leggere file da resources in Java con Google Guava

Leggere file da resources in Java con Google Guava

La cartella resources è molto usata nella programmazione Java e affini.

La lettura di file in questa cartella è possibile anche senza librerie, ma Google Guava ci offre un metodo molto veloce.

Se usate Maven aggiungete questa dipendenza:

        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>31.1-jre</version>
        </dependency>

Io ho creato un file config.json con questo dentro:

{
  "nome": "mattepuffo"
}

Qui sotto il codice:

import com.google.common.io.Resources;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class Main {

    public static void main(String[] args) {
        try {
            URL url = Resources.getResource("config.json");
            String jsonString = Resources.toString(url, StandardCharsets.UTF_8);
            System.out.println(jsonString);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }

}

Enjoy!


Condividi

Commentami!