0

I have a project where I like to read data from json files. However, the files cannot be found. I have already tried the java directory, as well as src/main/resources. For reading the files I use:

InputStream is = new FileInputStream(file);

where file is the name of the file, eg. "test.json".

Is there a specific directory I need to use? When I use a directory like "c:\temp\test.json" it works.

For the project I'm using IntelliJ and Maven.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Cord
  • 45
  • 1
  • 6
  • Basically you can put them anywhere and adress them there. Tho perhaps you may want to give them in as a startargument? – pikkuez Jan 20 '20 at 11:14
  • https://stackoverflow.com/questions/1464291/how-to-really-read-text-file-from-classpath-in-java – Azodious Jan 20 '20 at 11:14
  • To open a **file** (opposed to a resource) using a relative path, that path must be relative to the current working directory of your program, see [Getting the Current Working Directory in Java](https://stackoverflow.com/questions/4871051/getting-the-current-working-directory-in-java) – Mark Rotteveel Jan 20 '20 at 11:26
  • Your program will look for a file named "test.json" in the current directory. – Maurice Perry Jan 20 '20 at 11:34

2 Answers2

1

import following

import java.net.URL;
import com.google.common.base.Charsets;
import com.google.common.io.Resources;    



public static String getFileAsString(String jsonfilename) throws IOException {
        URL url = Resources.getResource(jsonfilename);
        return Resources.toString(url, Charsets.UTF_8);
    }

keep file src/java/resource file

abhinavsinghvirsen
  • 1,853
  • 16
  • 25
0
InputStream is = Xxx.class.getResourceAsStream("/test.json");

Path relative to class's package folder, or absolute as here (/...). In maven under /src/main/resources.

URL url = Yyy.class.getResource("/test.json");
Path path = Paths.get(url.toURI());
String json = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138