Java 8 Solution

 Path source = Paths.get(this.getClass().getResource("/").getPath());
        Path newFolder = Paths.get(source.toAbsolutePath() + "/newFolder/");
        Files.createDirectories(newFolder);

This will surely create new folder in resource folder. but you will find new folder in your target runtime.

which will be ProjectName/target/test-classes/newFolder. if you are running this code in test case. Other wise it would be in target/classes

Don't try to find new folder in your src/resources. it will be surely in target/test-classes or target/classes.

Answer from Rohit Kumar on Stack Overflow
Top answer
1 of 6
15

Java 8 Solution

 Path source = Paths.get(this.getClass().getResource("/").getPath());
        Path newFolder = Paths.get(source.toAbsolutePath() + "/newFolder/");
        Files.createDirectories(newFolder);

This will surely create new folder in resource folder. but you will find new folder in your target runtime.

which will be ProjectName/target/test-classes/newFolder. if you are running this code in test case. Other wise it would be in target/classes

Don't try to find new folder in your src/resources. it will be surely in target/test-classes or target/classes.

2 of 6
11

As other people have mentioned, resources are obtained through a ClassLoader. What the two current responses have failed to stress, however, is these points:

  • ClassLoaders are meant to abstract the process of obtaining classes and other resources. A resource does not have to be a file in a filesystem; it can be a remote URL, or anything at all that you or somebody else might implement by extending java.lang.ClassLoader.
  • ClassLoaders exist in a child/parent delegation chain. The normal behavior for a ClassLoader is to first attempt to obtain the resource from the parent, and only then search its own resources—but some classloaders do the opposite order (e.g., in servlet containers). In any case, you'd need to identify which classloader's place for getting stuff you'd want to put stuff into, and even then another classloader above or below it might "steal" your client code's resource requests.
  • As Lionel Port points out, even a single ClassLoader may have multiple locations from which it loads stuff.
  • ClassLoaders are used to, well, load classes. If your program can write files to a location where classes are loaded from, this can easily become a security risk, because it might be possible for a user to inject code into your running application.

Short version: don't do it. Write a more abstract interface for the concept of "repository of resource-like stuff that I can get stuff from," and subinterface for "repository of resource-like stuff that I can get stuff from, but also add stuff from." Implement the latter in a way that both uses ClassLoader.getContextClassLoader().getResource() (to search the classpath) and, if that fails, uses some other mechanism to get stuff that the program may have added from some location.

🌐
Coderanch
coderanch.com › t › 669663 › java › load-write-file-getClass-getResource
load/write file with getClass().getResource() is working in Eclipse, but not working in jar (I/O and Streams forum at Coderanch)
Am I using the wrong methods to construct the java.io.File for manipulation? ... Sorry I forget to switch to I/O subforum. If anyone can move this post to there, it's appreciated. ... If you put the resource into a JAR then you can't expect to access it as if it were a file. Sure, you can read from it but you can't write to it because a JAR is a read-only thing.
🌐
YouTube
youtube.com › vlogize
How to Write a File to the Resource Folder in Java Spring Boot - YouTube
Disclaimer/Disclosure: Some of the content was synthetically produced using various Generative AI (artificial intelligence) tools; so, there may be inaccurac...
Published   April 24, 2024
Views   352
🌐
JetBrains
intellij-support.jetbrains.com › hc › en-us › community › posts › 360000655999-Creating-or-jumping-to-a-resource-folder-for-a-given-class
Creating or jumping to a resource folder for a given class – IDEs Support (IntelliJ Platform) | JetBrains
If that folder doesn't exist yet I copy the relative path of the java file, remove everything before "src", navigate to the resources folder, create a new folder and paste the path.
🌐
Sde-coursepack
sde-coursepack.github.io › modules › java › File-Resources
SDE | File Resources
First, I open up a text editor and write the file contents: A Haiku for my cat: Chloe, calico, Why do you stand on shoulders? I'm trying to work! Now, wherever I saved that file, I’m going to copy and paste (or click and drag) the file into my project’s src/main/resources folder: The following code is a complete program to open and read a resource file: import java.io.*; public class FileResourceExample { private static final String RESOURCE_FILENAME = "chloe.txt"; public static void main(String[] args) { FileResourceExample example = new FileResourceExample(); example.run(); } public void
Find elsewhere
🌐
Mkyong
mkyong.com › home › java › java – read a file from resources folder
Java - Read a file from resources folder - Mkyong.com
September 4, 2020 - 1.2 By default, build tools like Maven, Gradle, or common Java practice will copy all files from src/main/resources to the root of target/classes or build/classes. So, when we try to read a file from src/main/resources, we read the file from the root of the project classpath. 1.3 Below is a JAR file structure. Usually, the files in the resources folder will copy to the root of the classpath.
Top answer
1 of 2
6

You can output text to a file in the resources folder, but the process is a bit tedious.

  1. Tell Maven to write the location of your resources folder into a file
  2. Read the location of your resources folder in Java
  3. Use that location to write your file to

Notes

  • Why bother specifying the location of your resources folder file? Isn't it src/main/resources always? Well no, if you have a nested module structure like

    rootModule   
    ├─ childModule1   
    │  └─ src    
    │     └─ main    
    │        └─ resources    
    └─ childModule2 
       └─ ...  
    

    then the relative path src/main/resources resolves to parentModule/src/main/resources which does not exist.

  • Once you write the file to the resources folder, it will not be accessible through Class.getResource(). Class.getResource() provides you with read access to files located in your classpath. The files located in your resources folder are "copied" to your binary output folder (read classpath) during "compilation". In order to access your newly created resource file with the help of Class.getResource(), you will have to recompile & restart the application. However, you can still access it by the location you used for writing the file.

Guide

  1. add RESOURCE_PATH property to the Maven pom, and tell Maven to compile properties found in resource files
  2. add an utility file src/main/resources/RESOURCE_PATH, which only contains the RESOURCE_PATH property
  3. extract the RESOURCE_PATH property from the utility file in Java
  4. rebuild the project if needed (e.g. if file/folder structure changes)

POM

<project>
    ...
    <properties>
        <RESOURCE_PATH>${project.basedir}/src/main/resources</RESOURCE_PATH>
    </properties>
    ...
    <build>
        ...
        <resources>
            <resource>
                <directory>${RESOURCE_PATH}</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
        ....
    </build>
    ...
</project>

Utility file (src/main/resources/RESOURCE_PATH)

${RESOURCE_PATH}

Java

/**
 * Reads the relative path to the resource directory from the <code>RESOURCE_PATH</code> file located in
 * <code>src/main/resources</code>
 * @return the relative path to the <code>resources</code> in the file system, or
 *         <code>null</code> if there was an error
 */
private static String getResourcePath() {
    try {
        URI resourcePathFile = System.class.getResource("/RESOURCE_PATH").toURI();
        String resourcePath = Files.readAllLines(Paths.get(resourcePathFile)).get(0);
        URI rootURI = new File("").toURI();
        URI resourceURI = new File(resourcePath).toURI();
        URI relativeResourceURI = rootURI.relativize(resourceURI);
        return relativeResourceURI.getPath();
    } catch (Exception e) {
        return null;
    }
}

public static void main(String[] args) throws URISyntaxException, IOException {
    File file = new File(getResourcePath() + "/abc.txt");
    // write something to file here
    System.out.println(file.lastModified());
}

I hope that works. Maybe you need maven resources:resources plugin and do mvn generate-resources process-resources

2 of 2
0

You can override the file but that would only work in IDE, if it would be executed as part of jar it would fail because it is not a file any more( its file inside file)

Better to externalize file and read/overwrite from that location

If you still would like to read this file and overwrite it then you can do something like

Thread.getclassloader().get resource("/");

This will give you path up to your target/classes directory you can navigate to resources from here using double dots

🌐
Coderanch
coderanch.com › t › 729642 › java › Read-write-text-file-IDE
Read/write to text file in IDE or getResource in JAR (using same source code) (Java in General forum at Coderanch)
I notice you have a different layout, but I do see a resource folder. Put the file in there, then you should be able to read it as a resource. SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6 - OCEJPAD 6 How To Ask Questions How To Answer Questions ... After Rob's suggestion the path should be "/" + fileName. JavaRanch-FAQ HowToAskQuestionsOnJavaRanch UseCodeTags DontWriteLongLines ItDoesntWorkIsUseLess FormatCode JavaIndenter SSCCE API-17 JLS JavaLanguageSpecification MainIsAPain KeyboardUtility
🌐
How to do in Java
howtodoinjava.com › home › i/o › read a file from resources directory
Read a File from Resources Directory - HowToDoInJava
December 8, 2022 - When packaging the application as war file, the file present in the '/resources' folder are copied into the root '/target/app-name' folder. After the deployment in an application server, the war files are extracted in a server work directory. So, in this case, we are reading the file outside a zipped archive so we can refer to the file using a relative path.
🌐
Stack Overflow
stackoverflow.com › questions › 30503576 › reading-and-writing-to-file-in-resource-folder-maven
java - Reading and Writing to file in resource folder Maven - Stack Overflow
May 28, 2015 - public class PropertyFileReader { private static final Logger LOGGER = LoggerFactory .getLogger(PropertyFileReader.class); private static Properties prop; static { prop = new Properties(); } public static void main(String[] args) { String property = read("config.properties", "number"); System.out.println(property); write("config.properties", "number", "6"); } public static String read(final String fileName, final String propertyName) { File file = getpropertyFile(fileName); try (InputStream input = new FileInputStream(file)) { prop.load(input); } catch (IOException ex) { LOGGER.error("Error oc
🌐
ZetCode
zetcode.com › java › createfile
Java create file - learn how to create a file in Java
package com.zetcode; import java.io.File; import java.io.IOException; public class JavaCreateFileEx { public static void main(String[] args) throws IOException { File file = new File("src/main/resources/myfile.txt"); if (file.createNewFile()) { System.out.println("File has been created."); } else { System.out.println("File already exists."); } } }
🌐
Coderanch
coderanch.com › t › 757738 › java › resources-folder
How to get resources folder (Beginning Java forum at Coderanch)
December 29, 2022 - In a ZIP (JAR) file, as I said, ... methods to walk the JAR's directory and read the resources. You cannot write into a JAR except by making a new copy of the JAR file with the changes added to the new copy....
🌐
Java2Blog
java2blog.com › home › core java › java file io › read a file from resources folder in java
Read a file from resources folder in java - Java2Blog
January 12, 2021 - In this post, we will see how to read a file from resources folder in java. If you create a maven project(simple java or dynamic web project) , you will see folder src/java/resources.
🌐
Stack Overflow
stackoverflow.com › questions › 69824169 › write-string-to-file-in-the-resources-folder
java - Write string to file in the resources folder - Stack Overflow
The source folders are different than the target folders that are used at runtime. Using Eclipse, when examining the contents of resource.toURI(), you should get a value of something like target\test-classes\file.json. That is the location of the resource at runtime. You can write to that location, but it will not change the contents of your original source file. Using Eclipse, the location of the original source is src\test\java\file.json