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.

4
  • Basically you can put them anywhere and adress them there. Tho perhaps you may want to give them in as a startargument? Commented Jan 20, 2020 at 11:14
  • stackoverflow.com/questions/1464291/… Commented Jan 20, 2020 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 Commented Jan 20, 2020 at 11:26
  • Your program will look for a file named "test.json" in the current directory. Commented Jan 20, 2020 at 11:34

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.