FileNotFoundException in src/main/resources
If you're going to package the file in the class path, then read it as such.. from the class path.
Maven Structure
src
main
resources
file.txt
After it builds, the file gets placed in the root of the class path. So use
InputStream is = getClass().getResourceAsStream("/file.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
The /
in front of file.txt
will bring you to the root, from whatever package the class is in.
UPDATE
Test example
package com.underdogdevs.stackoverflow;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class TestResourceFile {
public static void main(String[] args) throws IOException {
InputStream is = TestResourceFile.class.getResourceAsStream("/test.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
}
java.io.FileNotFoundException: src\main\resources\Report\testQuery.xlsx (The system cannot find the path specified) after deploying file in tomcat
Folder src\main\resources\Report does not exist when you deploy the application to Tomcat. When the project is built, compiled classes and resources are packed into a WAR archive. On runtime, you can access resources from the /resources folder, but you cannot write there.
You need to find some other location for the generated files, ensuring that it will be available for your application when deployed to the application server.
- If the files are temporary, you can use
File.createTempFile
, which is pretty safe to be used in any environment. - You can use your application's working directory, whatever it is. In your IDE it would be your project's root folder (that's why src\main\resources\Report\testQuery.xlsx works), on Tomcat it depends on the server configuration (CATALINA_BASE environment variable). You could create there a /Report subdirectory on the application startup.
Error Caused by: java.io.FileNotFoundException for file under src/main/resources/config/env/dev2 in SpringBoot 2.0 application
Never access the resources from the classpath like that. Use Class.getResourceAsStream
or ClassLoader.getResourceAsStream
:
BufferedReader br = new BufferedReader(
this.getClass().getResourceAsStream("path/relative/to/classpath/resource.file")
);
FileNotFoundException exception when reading from a HTML resource
verification.html
looks rather like a "class path resource" than a file...
(A file is very environment dependent (e.g. thinking of its path/location), whereas a "CPR" we package & supply with our application & can refer to it with a known&fixed (absolute or relative) (class path) address.Nor maven nor gradle (by default) "includes" anything else from
src/main/java
than*.java
files. So please move the according files (including structure/packages) tosrc/main/resources
(orsrc/test/...
accordingly).When the resource is finally in classpath, since spring:3.2.2, we can do that:
String emailBody = org.springframework.util.StreamUtils.
copyToString(
new org.springframework.core.io.ClassPathResource(
"/full/package/of/emailTemplate/EmailVerificationTemplate/verification.html")
.getInputStream(),
/* you must know(!), better: */
Charset.forName("UTF-8")
);(..also outside/before spring-boot-application.)
In spring context, the
Resource
(Classpath
-,ServletContext
-,File
(!)-,URL
-, ...) can also be "injected", like:@Value("classpath:/full/package/...")Resource verificationEmailBody
..instead of calling the constructor.
See also:
- Spring Core#Resources reference doc
Resource
javadoc- How do I read / convert an InputStream into a String in Java?
- How do I load a resource and use its contents as a string in Spring
When you need to refer to verification.html
as a File
, then please ensure:
It has a distinct (absolute (ok!) or relative (good luck!)) address (in all target environments)!
Java FileNotFoundException when trying to read txt file from resources folder
The idea of putting something into the src/main/resources tree is that it will be copied into the JAR file that you build from your project. It will then be available to your application via the Class
methods getResource(String)
and getResourceAsStream(String)
methods.
When you are running in your application in the development environment, it is certainly possible to use FileInputStream
etcetera to access the resource. But this won't work in production. In production, the resources will then be inside your app's JAR file. FileInputStream
cannot open a JAR file and its contents by name.
When you do this:
getClass().getResource("/text/file.txt");
you get a URL for the resource, which will look something like this:
jar:file:/path/to/your.jar!/text/file.txt"
It is not possible to turn that into a pathname the FileInputStream
will understand. Whatever you try will give you a FileNotFoundException
... or something that is not the resource you want to read.
So what to do?
You have a few options, depending on your application's requirements.
You can use
getResourceAsStream
and use the resulting input stream directly.You can copy the contents of
getResourceAsStream
to a temporary file, and then use the pathname of the temporary file.You can create an application specific directory (e.g. in the user's home directory) and extract the file you need from the JAR into the directory. You might do this the first time the application runs.
You could open the JAR file as a
JarFile
and use that API to open anInputStream
for the resource. But this assumes that that the resources are in a JAR ... and on some platforms (e.g. Windows) you may encounter problems with file locking. (And it would be a bad idea to attempt to update the resource in the JAR.)
FileNotFoundException starting jar - can't see file in resources folder
src/main/resources is maven convention to have resources file. When maven build jar/war artifact, it adds all files/directories from src/main/resources to classpath of resulting artifact.
There is no src/main/resources available at runtime.
In your case, you can update your program to read these files without giving any path. like below
private static final String RELATIVE_PATH_TO_PROPERTIES = "config.properties";
public static final String RELATIVE_LOG_PATH = "err_action.log";
Related Topics
Converting Exponential Value in Java to a Number Format
How to Run Single Cucumber Feature Files Through Command Prompt and Through Jenkins Using Maven
Java8 Way to Handle If..Else Check in Collections
Java Properties - How to Create Dynamic Properties
Connect to Remote MySQL Database Through Ssh Using Java
Spring Data JPA Saveall Not Doing Batch Insert
How to Find the Number of Times If or Else Code Has Executed
Sending Variable from Adapter to Activity
How to Split Single Row into Multiple Rows in Spark Dataframe Using Java
How to Find Out My MySQL Url, Host, Port and Username
How to Resolve Java.Lang.Noclassdeffounderror: Javax/Xml/Bind/Jaxbexception
Handling Static Variables in Multithreaded Java Program
Convert Html/Mxml File to Word Doc Programmatically in Java
Java Input Validation for Number Range and Numeric Values Only With Counter
I Want to Get Time Difference Between Two Time in Milisecond