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.

🌐
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.
🌐
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 › 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)
Y:\CtrlRecau_WinSuite_DYL\desarrollo\workspace_NEW\CalSaldoFichaje\bin\com\WindThunderStudio\resources\inputData.txt But, if I pack this project as a runnable JAR and run it in Windows OS, it's different. When writing data, the constructed file's absolute path is: d:\desarrollo\file:\D:\desarrollo\Cal6.jar!\com\WindThunderStudio\resources\inputData.txt and its path(calling file.getPath()) is:
🌐
Baeldung
baeldung.com › home › java › java io › java – create a file
Java - Create a File | Baeldung
August 29, 2024 - In this quick tutorial, we’re going to learn how to create a new File in Java – first using the Files and Path classes from NIO, then the Java File and FileOutputStream classes, Google Guava, and finally the Apache Commons IO library. This article is part of the “Java – Back to Basic” series here on Baeldung. In the examples, we’ll define a constant for the file name: private final String FILE_NAME = "src/test/resources/fileToCreate.txt";
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 31297503 › creating-a-new-folder-in-resources-folder-and-read-write-text-files-there-maven
java - Creating a new folder in resources folder and read-write text files there (Maven Project) - Stack Overflow
May 22, 2017 - Resources below src/main/resources/ end up in the JAR file which Maven creates - Java wants it that way. They aren't visible anymore as files when you run the JAR. That's why you can't create a path to them. To access the resources, you need to ask the ClassLoader for a URL (.getResource("...relative/path...")) or an InputStream (getResourceAsStream()). If you want to save config options, you should use the Preferences API or maybe create a Properties file in the home folder of the user or in a folder defined by a system property.
🌐
Sde-coursepack
sde-coursepack.github.io › modules › java › File-Resources
SDE | File Resources
In this module, we will first look at some simple usage of resource files in Java. Second, we will look at some basic File I/O in Java for reading and writing to Plain Text files (like .txt or .csv). ... Creating a simple text file.
🌐
DigitalOcean
digitalocean.com › community › tutorials › java-create-new-file
Java create new file | DigitalOcean
August 4, 2022 - There are three popular methods to create file in java. Let’s look at them one by one. java.io.File class can be used to create a new File in Java. When we initialize File object, we provide the file name and then we can call createNewFile() method to create new file in Java.
🌐
YouTube
youtube.com › watch
How to create a Resource folder in Java with IntelliJ and how to access it - YouTube
I will be showcasing how to create a resource folder in Intellij, and I will create a method that readers a file form the resource folder and print the input...
Published   March 5, 2021
🌐
Stack Overflow
stackoverflow.com › questions › 24790398 › create-file-inside-folder-resources-of-spring-project
java - Create file inside folder "resources" of spring project - Stack Overflow
public boolean upload_picture(E e, MultipartFile f) { Integer id = null; if(f == null) { return false; } Class<?> clazz = e.getClass(); Method methods[] = clazz.getDeclaredMethods(); for(int i=0; i<methods.length; i++) { if(methods[i].getName().equals("getId")) { try { id = (Integer) methods[i].invoke(e); } catch (IllegalAccessException e1) { e1.printStackTrace(); return false; } catch (IllegalArgumentException e1) { e1.printStackTrace(); return false; } catch (InvocationTargetException e1) { e1.printStackTrace(); return false; } } } BufferedImage src; try { src = ImageIO.read(new ByteArrayInp
🌐
JetBrains
intellij-support.jetbrains.com › hc › en-us › community › posts › 15856892325394-How-can-I-create-a-new-resource-file-from-an-IntelliJ-Idea-plugin
How can I create a new resource file from an IntelliJ Idea plugin? – IDEs Support (IntelliJ Platform) | JetBrains
December 18, 2023 - @Override public void invoke(@NotNull Project project, Editor editor, PsiFile psiFile) throws IncorrectOperationException { // here should be located the code to create a file for IntelliJ } ... @Override public void invoke(@NotNull Project project, Editor editor, PsiFile psiFile) throws IncorrectOperationException { for (VirtualFile virtualFile : ProjectRootManager.getInstance(project).getContentRoots()) { String path = virtualFile.getPath(); if(path.endsWith("main")) { VirtualFile resDirectory = virtualFile.findOrCreateChildData("any_requestor", "resources"); PsiDirectoryFactory.getInstance(project) .createDirectory(resDirectory) .createFile("your_file_here") .getVirtualFile().setBinaryContent("content_of_your_file".getBytes(UTF_8)); } } // your_code_HERE }
🌐
Chief Delphi
chiefdelphi.com › technical › java
How to create a "resources" directory from gradle? - Java - Chief Delphi
January 17, 2020 - I want to write some data using gradle into the src/main/resources directory to be included int he deployed jar file. I have it working if the resources directory is already there, but is there a way to get gradle to create the directory if it isn’t already there?
🌐
Mkyong
mkyong.com › home › java › java – read a file from resources folder
Java - Read a file from resources folder - Mkyong.com
September 4, 2020 - We cannot read the files inside the JAR file via the resource URL. Run the JAR file on Linux (Ubuntu), it throws NoSuchFileException. ... $ mvn clean package $ java -jar target/java-io.jar getResourceAsStream : json/file1.json { "name": "mkyong", "age": 38 } # for new File(resource.getFile()); getResource : json/file1.json java.nio.file.NoSuchFileException: file:/home/mkyong/projects/core-java/java-io/target/java-io.jar!/json/file1.json at java.base/sun.nio.fs.UnixException.translateToIOException(UnixException.java:92) at java.base/sun.nio.fs.UnixException.rethrowAsIOException(UnixException.ja