I'm trying to create a basic Java program that allows the user create files and folders.
I want all this to happen in a folder inside my project (image attached) so I've got some doubts...
This would be my proyect tree
Is the folder "Test" correctly placed? if not how do i access to it? As you see, it's inside com.company, should I move it to src?
When I try to check if exists, it says false.
This is my code:
public class Main {
Scanner input = new Scanner(System.in);
public static void main(String[] args) {
Main main = new Main();
main.init();
}
public void init(){
File f = new File("Test"); //Here i've tried "com"+File.separator+"company"+File.separator+"Test"
System.out.println(f.exists()); //output is false here
}
}
f.getParent() says null.
But when I try: System.out.println(f.getAbsolutePath()); it shows correctly the whole path.
The point of using relative path is because i'd like this code to work on ANY computer.
Thanks in advice, hope someone could help me a bit.
If you use relative pathnames in Java, they will be resolved relative to the running application's working directory. So you need to know what the working directory is going to be.
When you are launching an application in an IDE, the working directory depends on the IDE and the launcher configs. But it is typically the file system directory that corresponds to the top of the project.
Another thing to note is that the src folder you see is special. The entries in it are typically not files and directories. The are typically Java packages and classes. So in the file system, "src" > "com.company" > "Main" is actually represented as a file with the path "src/com/company/Main.java".
This means that it is kind of wrong to put arbitrary folders and files into the "src" folder. It will work ... but it is conceptually wrong. Data files don't belong in the source tree, and certainly not data files written by your application. (And when you start using a source control system, you will find that writing data files into your source tree is going to give you a headache. I won't go into details ... but I am pretty sure that you would regret it.)
The other thing that is conceptually wrong about what you are doing is that Java programs are normally written to be free standing things. The user of your program should not need to download and install Intellij or some other IDE and load your project into it. They will want to just run it from a JAR file. In that world, the project directory and the "src" folder won't exist, and hardwiring relative paths like "src/Test" will be problematic.
So lets ignore that for now and look at what your code is currently doing
Is the folder "Test" correctly placed? if not how do i access to it? As you see, it's inside com.company, should I move it to src?
According to the image, the Test folder (actually package) >>is<< in the src Folder.
When I try to check if exists, it says false.
Your code is using the wrong path. With the "Test" folder places where you have it (according to the picture!), the relative path should be "src/Test", not "Test" or "com/company/Test".
Note that Windows accepts either "/" or "\" will work as a file separator, even though "\" is what is used conventionally.
f.getParent() says null.
That is correct. The relative path "Test" does not have a parent part. It is a simple file / directory name.
Think of it this way. Until a File with a relative path is resolved, it is not determined what directory it is relative to.
But when I try: System.out.println(f.getAbsolutePath()); it shows correctly the whole path.
Again, correct.
When you call f.getAbsolutePath() on a relative File, the runtime system prepends the path of the application's working directory, and then gives you the result.
The point of using relative path is because I'd like this code to work on ANY computer.
That relative path will NOT work on ANY computer. You are using a path that is within your project's src tree, and your project typically won't exist on an end-user's computer. (See above.)
So what should you do?
There is no single correct answer.
You could put the file / directory into the user's current / working directory.
You could put the file / directory into the user's home directory, or a hidden subdirectory in the home directory. (This is a common approach on Linux.)
You could make the pathname for the directory a command line argument
You could get the pathname from an environment variable
You could get the pathname from an application specific config file.
The best answer will depend on the context.
According to your picture the path is wrong, you should check inside the src directory:
File f = new File("src/Test");
System.out.println(f.exists());
I am developing a maven project with Spring mvc application with Eclipse. I have some cucumber-selenium test case to check the some behavior of app. I put the chromDriver.exe in the path target\classes\Driver.
When i want to run the application it complains about:
The project was not built due to "Could not delete '/CyberMall/target/classes/Driver'.". Fix the problem, then try refreshing this project and building it since it may be inconsistent CyberMall Unknown Java Problem
It seems that, it tries to delete the Driver folder inside the target, and it fails, so it cannot build the application.
So, is there any way to ask Eclipse to stop deleting the Driver folder?
The reason I have put the driver in this path is that, i can easily access to it using the below code.
File file = new File(CyberMallApplication.class.getClassLoader().getResource("Driver/chromedriver.exe").getFile());
String driverPath=file.getAbsolutePath();
System.out.println(driverPath);
System.setProperty("webdriver.chrome.driver",driverPath);
If i put it into the resources, i don't know how to access it?
I think it's not a good practice to put a file that should be used in the targer folder.
The target folder should be clean at every maven install so the content is deleted.
You can put your file in the resources folder insted.
Take a look at that link : https://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html
The target directory is used to house all output of the build.
The content of the resource directory will be put inside WEB-INF/classes. So you can adapt your resources folder to have your folders like you already have.
resources/Driver/chromedriver.exe
You should put chromedriver.exe to src/main/resources and set relative path in the system properties
System.setProperty("webdriver.chrome.driver", "src/main/resources/chromedriver.exe");
I want to get the path to a resource for ImageIO to read out a BufferedImage from some .png s.
While developing the project I use a relative path to "/bin/stuff/icons/image.png" , but this will definetly not work when I put everything together into a .jar file, so I need a way to get the path to these resources both while testing in eclipse and when later running it within a .jar .
After a lot of trying out both finding the file and getting the input stream to the file I came to the conclusion that this approach works every time:
InputStream in = ClassLoader.getSystemClassLoader().getResourceAsStream(path)
BufferedImage image = ImageIO.read(in)
Where path is
"projectName/resourceFolder/" + nameOfResource.stuff
as found in the src directory of the eclipse project.
E.g.
"myProject/images/icon.png"
When getting only the resource and then getting the path of the resource to link to a file, you will get FileNotFoundExceptions when using a .jar (but not while testing with eclipse, so one should be warned to think that his code works).
And - no - I don't save images in the bin/ - but they are copied to this directory and thus I find them there while testing. Now everything seems to be working.
Don't put anything under the bin directory in Eclipse: if you run a clean on the project it will be erased.
What you can do is to define a new source folder like resources, and put the image there. This way it will be automatically copied to the bin folder.
If you include the resources folder into the Jar, it will be available in both environments by using something like:
ImageIO.read( getClass().getResource("/image.png") )
PS: You can evade using a different resources folder but mixing the sources and images will quickly pollute your source folder.
I keep getting this error every time I run my OpenGL program and try and set up a texture:
Unable to read texture file: java.io.FileNotFoundException: bricks.gif (No such file or directory)
I have the file bricks.gif in the same folder and it shows up in Eclipse as well, but I have no idea what is going on. I tried to clean and refresh as well, but nothing.
Any help would be greatly appreciated.
Two ideas for solving your problem:
Make the reference to bricks.gif absolute, adding the full path.
(e.g. /Users/abc/workspace/bricks.gif)
When Eclipse starts your Application, the directory root will be your project folder.
Think of the following layout in Eclipse Package Explorer:
projectname
-src
-bin
-...
-bricks.gif
You can refer to the file in relative way by using the path "./bricks.gif". You can obtain a File Object pointing to bricks.gif with the following code:
File bricks = new File("./bricks.gif");
or
File bricks = new File("bricks.gif");
Cheers
I am using the following to get the URL of this particular file, but it returns null. Does anyone have any suggestions as to the problem or an alternate way to do this?
URL url = ExchangeInterceptor.class.getResource("GeoIP.dat");
For those who use Intellij Idea: check for Settings > Build, Execution, Deployment > Compiler > Resource patterns.
The setting contains all extensions that should be interpreted as resources. If an extension does not comply to any pattern here, class.getResource will return null for resources using this extension.
The path is relative to the classpath root and if you don't give an absolute path, it is looking in the same package as the class you're using (in this case ExchangeInterceptor). To find something in the root use /GeoIP.dat.
Use the getResource method of the class' ClassLoader
URL url = ExchangeInterceptor.class.getClassLoader().getResource("GeoIP.dat");
I solved this problem by pointing out the resource root on IDEA.
Initially the directory was so and the icon was a plain folder icon
Before
Right click on a directory (or just the project name) -> Mark directory As -> Resource Root.
After
Recompile & rejoice :P
I've faced with the similar problem. From Java SE API for getResource(String name) :
If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'.
So I've added '/' before my directory : MyClass.class.getResource("/dir_name/").
In your case try to add '/' before your file name:
URL url = ExchangeInterceptor.class.getResource("/GeoIP.dat");
If you're using Gradle and IntelliJ, and changing Resource patterns didn't work, and your resource roots are set correctly...you can try this:
Settings > Build, Execution, Delpoyment > Build Tools > Gradle > Runner > Delegate IDE build/run actions to gradle. (IntelliJ 2017.3.3)
Source: https://youtrack.jetbrains.com/issue/IDEA-176738#comment=27-2518612
Just in case someone still has problems to understand that:
.getResource() grants you access to the local bin folder. That means, your resources need to be located in YourProject/bin/package/. The root folder is YourProject/bin/ and can be accssed by adding the prefix / to the String argument, like iirekm said.
No, that is the right way afaik. Make sure the resource is on your classpath. This is often the cause of these types of problems.
While using IntelliJ, I generated the project as a JavaFX app and then added maven framework support to it. Turns out, I then placed my resource in src/main/resources and had to add ./ behind every resource name that while using them in the code.
Also as stated in a previous answer, only loading the resource by a classLoader worked.
So for me, the final URL loading was done using:
URL url = getClass().getClassLoader().getResource(String.format(".%ssample.fxml", File.separatorChar));
The File.separatorChar returns / on *nix and \ on windows.
This is my example solution. Work for me.
The project structure:
• Source Packages
• game
• Game.java
• game.images
• tas_right.png
In the game class:
URL path=this.getClass().getClassLoader().getResource("images/tas_right.png")
Where do you have put this GeoIP.dat? In the same package as ExchangeInterceptor, or in the "root" package. If in the same package, your code is OK, if in the root - add '/' prefix.
Maybe you're using M2Eclipse? If configured incorrectly, it also may result in such problems. Another cause of such problems may be: misconfigured classloaders, misconfigured OSGi, ...
The file needs to be in the classpath, e.g.: -
bin/my/package/GeoIP.dat
The / prefix seems to be a lie. The following would work.
URL url = ExchangeInterceptor.class.getResource("my/package/GeoIP.dat");
I suspect the issue is that you do not have the file in the classpath.
I was able to fix it by adding "./" to the beginning of the file like this:
getClass().getClassLoader().getResource("./file.txt")
Instead of having the resource file in the same folder as your source files, create a resources folder parallel to the java source folder.
Before:
src
main
java
MyClass.java
file.bin
file.txt
After:
src
main
java
MyClass.java
resources
file.bin
file.txt
I use Intellij version Ultimate 2019.3
Go to
Settings -> Compiler -> Resource patterns.
Click ok.
Rerun Application/Server.
In my case, i included the jks in the project!
say you have :
titleLabel.setIcon(new ImageIcon(getClass().getResource("/uz/assets/icon.png")));//wrong !!
rightclick on the folder(mine is assets) an set Mark Directory as Resources
if you dont see that rightclick on project name and pickup Open module settings
Rightclick on resorces folder(assets in my case)
and select 'Resources'
Now go back to the above java instruction and remove path BUT leave /
like:
titleLabel.setIcon(new ImageIcon(getClass().getResource("/icon.png")));// correct one
A warning to all using the Path or Paths classes in Java: if you are on the god forsaken operating system known as Windows you will not be able to use Path.of or Paths.get as this will put backslashes in your path which Java will attempt to load and promptly fail. Instead use this:
Path.of(paths...).toString().replace(File.separator, "/")
You should always use this as it is OS independent. If anyone has a better or built in way please comment, I was unable to find one.
Strangely effective in my case (IJ 2022.1.4) was: close project (for example, quit IDEA), delete the /.idea folder completely (egg, rm -rd .idea), open project. When it re-imports the project, it runs as expected. Note: you loose about everything not included in gradle configs.
I realized using new File(location) works just fine in #dev and can also access files outside the /project folder
In case of eclipse.
Just a hint. Your code could be correct, but your jre configuration not. I ran into the the same error, nothing helped, until i checked the eclipse settings.
Make sure, that you set your execution environment right.
Preferences -> Java -> Installed JREs -> use "jdk..." as compatible JRE
First, you need to make sure you are accessing the right file on the right path. You can verify that by getClass().getResource("GeoIP.dat").getAbsolutePath().
Secondly, the path specifier is case-sensitive, so make sure your file is not named "geoIP.dat" or "GeoIP.DAT".