Reputation: 36672
my java test code tries to get to a file in my project folders
but I get IO exception:
String fileContents = new String(Files.readAllBytes(
Paths.get("src/test/resources/SenegalAndBulgariaConfig.txt")));
String fileContents = new String(Files.readAllBytes(
Paths.get("src/")));
It used to work, but not anymore:
java.nio.file.NoSuchFileException: src/test/resources/SenegalAndBulgariaConfig.txt
at sun.nio.fs.UnixException.translateToIOException(UnixException.java:86)
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:102)
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:107)
at sun.nio.fs.UnixFileSystemProvider.newByteChannel(UnixFileSystemProvider.java:214)
at java.nio.file.Files.newByteChannel(Files.java:361)
at java.nio.file.Files.newByteChannel(Files.java:407)
at java.nio.file.Files.readAllBytes(Files.java:3152)
though it exist:
Upvotes: 2
Views: 6565
Reputation: 91
private String readFileContent(String filePath) throws URISyntaxException, IOException {
byte[] bytes = Files.readAllBytes(Paths.get(getClass().getClassLoader().getResource(filePath).toURI()));
return new String(bytes);
}
in your case filePath will be SenegalAndBulgariaConfig.txt.
for example:
String senegalAndBulgariaConfig = readFileContent("SenegalAndBulgariaConfig.txt");
Upvotes: 1
Reputation: 3834
The following should work, assuming that SenegalAndBulgariaConfig.txt
is in /resources
:
InputStream is = getClass().getResourceAsStream("/SenegalAndBulgariaConfig.txt");
StringWriter writer = new StringWriter();
IOUtils.copy(is, writer, Charset.defaultCharset());
String fileContents = writer.toString();
System.out.println(fileContents );
NOTE getClass()
can be replaced by ClassName.class
Upvotes: 0
Reputation: 4598
There is often a confusion between loading files as resources (through classpath) or by addressing it directly on the drive. Maybe my answer here can help you distiguish the both.
Upvotes: 0
Reputation: 309008
You should never depend on File
. Load InputStream
from classpath.
Both src/main/resources and src/test/resources are in the classpath if you use the Maven standard directory structure.
I tend to like the Apache Commons IO library and Spring ClassPathResource
.
Upvotes: 1