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.
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.
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.
The src/main/resources folder is a folder that is supposed to contain resources for your application. As you noted, maven packages these files to the root of your file so that you can access them in your library.
Have a look at the Maven documentation about the standard directory layout.
In certain cases, it is possible to write to the context but it is not a good idea to try it. Depending on how your webapp is deployed, you might not be able to write into the directory. Consider the case when you deploy a .war archive. This would mean that you try to write into the war archive and this won't be possible.
A better idea would be to use a temporary file. In that way you can be sure this will work, regardless of the way your web application is deployed.
Agree with Sandiip Patil. If you didn't have folder inside your resources then path will be /sudoinput.txt or in folder /folder_name/sudoinput.txt. For getting file from resources you should use YourClass.class.getResource("/filename.txt");
For example
Scanner scanner = new Scanner(TestStats.class.getResourceAsStream("/123.txt"));
or
Scanner scanner = new Scanner(new `FileInputStream(TestStats.class.getResource("/123.txt").getPath()));`
Also look at: this
If you want to create a test.xml file in the directory returned by getResource(), try this:
File file = new File(classLoader.getResource(".").getFile() + "/test.xml");
if (file.createNewFile()) {
System.out.println("File is created!");
} else {
System.out.println("File already exists.");
}
Calling getFile() on a non-existent directory or file will return null, as explained in Reid's answer.
It looks like your call to getResource("file/test.xml") is likely returning null.
I'm curious, what is the full path to your XML file? For this to work, the resources directory needs to be placed in your webapp directory. If you are trying to use the standard Java resources structure (src/main/resources) then that Spring MVC mapping will not work.
EDIT: After seeing your answer to @Ascalonian's comment, this will not work since the file doesn't exist. Like I mentioned earlier, getResource("file/test.xml") will return null so the following call to getFile() will throw the NPE. Maybe you should check if getResource returns null and use that as an indication that the file needs to be created.
Something is totally wrong if you are creating dynamically file in src/main/resources This is only going to work in your development environment. When you deploy your code using Jar or War there won't be this directory on file system. It will be contained within Jar / War or other packaging.
If you understand above and still want to do it. Go related to your current working directory to create file, Usually the working directory when you launch your Main from IDE is setup to root of project so create a file at
src/main/resources/foo.txt
will do it. Alternatively you can figure out your current working directory from your IDE launcher or at runtime using
System.getProperty("user.dir");
What are you exactly trying to achieve writing the JSON file to the mentioned directory ?
I might miss something important in your question but:
it is possible to create code that does this thing but i'm not sure at all how are you going to run this code and is it sane solution to your problem?
When you mvn package the project name P having this "src/main/resources/" resources there will be added to package P.war/.jar or so but there will not be any JSON-file in directory until you run the code - this code you are after - that generates it and it is not done without some -maybe ugly- extra job.
If you have this code included in this project it will be run only when the project package is run. And there will not be this "src/main/resources/" where to write it.
You can use java.utils to create a folder inside the resource directory
new File("/path/directory").mkdirs();
"directory" is the name for the folder you want to create
you can get the root of the classpath from new ClassPathResource(".").getFile().getPath() and after that you can append the folder name that you want. after Make the File object by using that full path. and then you can create a folder as you want in the class path.
File txtFile = new File(new ClassPathResource(".").getFile().getPath()+"/tmp");
if (!txtFile.exists()) {
txtFile.mkdirs();
}
When at the "Add resource folder",
Build Path -> Configure Build Path -> Source (Tab) -> Add Folder -> Create new Folder

add "my-resource.txt" file inside the new folder. Then in your code:
InputStream res =
Main.class.getResourceAsStream("/my-resource.txt");
BufferedReader reader =
new BufferedReader(new InputStreamReader(res));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
To answer your question posted in the title of this topic...
Step 1--> Right Click on Java Project, Select the option "Properties"
Step 2--> Select "Java Build Path" from the left side menu, make sure you are on "Source" tab, click "Add Folder"

Step 3--> Click the option "Create New Folder..." available at the bottom of the window
Step 4--> Enter the name of the new folder as "resources" and then click "Finish"

Step 5--> Now you'll be able to see the newly created folder "resources" under your java project, Click "Ok", again Click "Ok"

Final Step --> Now you should be able to see the new folder "resources" under your java project

Caveat: I don't use Eclipse, I've never used Eclipse, my knowledge of Eclipse amounts to reading other posts and answering questions here
Under your project, create a directory called resources. In here place all you "resources" you want to access from within your application. These will be bundled with your application as embedded resources.
From within your application use either
this.getClass().getResource("/ah.wav")
or
this.getClass().getResource("/resources/ah.wav")
Assuming that you placed the files at the top level of the resources path. If they're in a sub-directory, you'll need to provide the full path...
Clean, build and test
I'd create a resources folder inside src something like src/main/resources. You would like to take a look to Maven that is project management and comprehension tool that help a lot in project organization.