Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I have a problem or a question regarding Java and or Eclipse. I have a programm that does the following:
open up a UI where the user can search for a folder
if the folder is picked the absolut path is getting passed to the main
there are few folders in that chosen path
there are functions that read from the data and create a new excel with the read data
The path that I am getting is correct!
Gernerally the programm works... But it only works if:
The chosen Path from the User is a folder that is inside the project folder where I run the programm from.
OR
The Names of the files that are getting read are specified inside the project folder. What I mean with that is: if the file test.vcc is inside the package then I could open it from the desktop if there is a file that is also named test.vcc
So it seems like Java or Eclipse cant open up paths that are not inside the project or named in the project - is that true?
Running the programm gives me NullPointerExceptions for every File that is not especially named or inside the project.
Sincerly Faded
Update
Okay so I have noticed something that I am doing wrong definetly!
I was replacing the whole FILEPATH that the User choses with ".\" which obviouslly means that it will not care about the filepath and replace it with .\ instead of really taking the path.
String filePathS = filePath.replace(FILEPATH, ".\\");
When I am using this it works because it can find the files in the project Folder. So after seeing this I just took the real Path that the user choosed.
Its basically this:
String filePathSX = filePath.replace("/", "\\");
or this
String filePathSX = filePath.replace("\\", "/");
which either gives me a Path like this: C:\Users\me\dev\foldername\part\test.txt or like this C:/Users/me/dev/foldername/part/test.txt
I can check that in the destination the file test.txt does indeed exist and the path is correct. Still when it tries to do something with that file it gives me a NullPointerExeption.
IF I would leave the replace function for the whole path with .\, then it would take the test.txt file that is inside the package and it would run without any problems.
So I think that I am somehow accsessing the file in the wrong way. How should the path look like on windows if the user chooses something? c/user/... or c\user...
Because both ways do not work for me.
So it seems like Java or Eclipse cant open up paths that are not inside the project or named in the project - is that true?
Yes and no. But mostly no, that is not true.
Some OSes (most notably, Mac OS) have a security policy framework in place that denies any file access to all applications unless you explicitly allow it. If you're on a mac, that sounds like it could be the culprit.
Other than that, though - the answer is no: That is incorrect.
You'd have to ask a new question and provide a bunch of details if it's not the Mac OS thing: Show the code, show the result of printing the path, and show the actual file structure on disk, for example.
NullPointerException sounds even weirder, so maybe your code is just problematic.
This is not true...
File f = new File("C:\\path\\to\\your\\file");
// perform some checks here to make sure Desktop can actually open it
Desktop desktop = Desktop.getDesktop();
desktop.open(f);
EDIT: if you are getting NPEs, your path contains no file, try creating a file with a certain name at that location, and then opening it in your file explorer to see where it actually went
I want to use image files for my java program, and for that I need File objects. But I have the problem that when I build my project, the project name has a .jar at the end of the name, making a File object like new File("..\\Project\\src\\ImageDirectory\\Image.png") useless, since the directory doesn't exist.
I've found out I could tecnically iterate through all the directorys on the computer but I don't want to do that because that could take some time with high amounts of directories and harddrives.
So, is there a reliable and easy way to get the directory the jar file is currently in?
My IDE is InellijIDEA
You can use Path to do this:
Path path = Paths.get(YourMainClass.class.getProtectionDomain().getCodeSource().getLocation().toURI());
Path have several methods to get more information.
For example, i have this JAR in Desktop and i am printing this:
System.out.println(path);
System.out.println(path.getRoot());
System.out.println(path.getParent());
The results are:
java -jar C:\Users\gmunozme\Desktop\Test.jar
C:\Users\gmunozme\Desktop\Test.jar
C:\
C:\Users\gmunozme\Desktop
Check that out,
Hope you can use it.
I know there were several similar questions, however, examples in them don't make things clear or I can't make profit of them - Shame on me.
So my problem is with loading images in simple app with GUI.
e.g.:
I got images in "D:\javaeclipseprog\Graphics\src\images", class and java files in "D:\javaeclipseprog\Graphics\src\app"
When I use direct path: "D:/javaeclipseprog/Graphics/src/images/icon.jpg" everything works, but as good practice I would like to get them from relative path, which as far as I know should be: "./images/icon.jpg".
Unfortunately it doesn't work.
Any help appreciated, thanks in advance.
When you are running it in eclipse, your default working directory in the project directory. That is the directory where srcis located in. In your example the project directory is:
D:/javaeclipseprog/Graphics
Therefore the correct path is:
./src/images/trophy.png
Edit: Just want to add that you could also load a file via a path relative to the class location by using the getResource method.
../../images/icon.jpg should work fine
You're going two folders up and go straight to the right folder.
Paths
A simple way to check this would be to use the Paths and Path classes and methods.
Path p1 = Paths.get("D:\\javaeclipseprog\\Graphics\\src\\app\\java.class");
Path p2 = Paths.get("..\\..\\images\\icon.jpg");
System.out.println(p1.resolve(p2).normalize()); // D:\javaeclipseprog\Graphics\src\images\icon.jpg
I'll use the inverted slash because it seems that you use windows. In this case .\ indicates that the same directory where the code is, will have the file you want to use. If you want to jump into the father of that directory, the one that contains the source, you'll use ..\
You can even do it more tan once, for example ..\..\ would be a valid path. Try adding quantities of ..\ in order to look for the directory you want. In this chase ..\src\images\icon.jpg (the parent on a java project is src)
Another important thing is that you're using / instead of \\ that would be the symbol of the directory separator on windows (\ is an special char that must be scaped using an aditional \) For portability i'd use:
String sep = System.getProperty("file.separator");
String path = ".."+sep+"src"+sep+"images"+sep+"icon.jpg"
I think what you need to use is "../images/icon.jpg".
Using it like you have it will look in the current directory, which unless I'm understanding it incorrectly, is "D:\javaeclipseprog\Graphics\src\app".
Due to a project requirement I had to move from Selenium 2.0 to Watir and Cucumber framework. Earlier we were using Java and often set the default file path as:
System.setProperty("webdriver.chrome.driver",System.getProperty("user.dir")+"/browsers/chromedriver.exe");
Now I am trying to set up something similar in Ruby also, but being new to Ruby, I'm failing to get the root directory of the project. It only gets the path of the file which the current user is working using __FILE__ or Dir.pwd.
My Watir project structure is like this:
root
-config
-features
-pages
-step_definitions
-support
-hooks.rb
-browsers
...
...
I want to specify in hooks.rb that if the parameter passed is "Chrome", then run the Chrome browser, and when it is "FF" run the Firefox browser, but it always gives me the current working directory path and I need the root directory.
I am on WINDOWS 7, Using Ruby version 1.9.3p551.
Ruby's File class has several different methods that are useful for what you're trying to do, so read the documentation for absolute_path, expand_path, realdirpath and realpath.
I'd recommend starting with absolute_path:
Converts a pathname to an absolute pathname. Relative paths are referenced from the current working directory of the process unless dir_string is given, in which case it will be used as the starting point. If the given pathname starts with a “~” it is NOT expanded, it is treated as a normal directory name.
I built the path from your hooks.rb to the root directory in my tests directory on my Desktop, and added this code to hooks.rb:
PATH_TO_ROOT = File.absolute_path('../..', File.dirname(__FILE__))
Running it shows:
PATH_TO_ROOT # => "/Users/ttm/Desktop/tests/ruby/root"
You'll always have to maintain the '../..' relative string but that is easier than hard-wiring your code with a fixed absolute path.
I tend to put code similar to this in any project that has multiple directories, especially when I'm calling library files. Write your code correctly, and you can do it once assigning the value to a constant, and you can then reference that constant wherever you need to know the absolute path to the installation.
book = Roo::Excel.new(File.join(File.absolute_path('../..', File.dirname(__FILE__)),"config/data/test.xls"))
It's a lot easier than that:
path_to_book = File.absolute_path('../../config/data/test.xls', File.dirname(__FILE__))
path_to_book # => "/Users/ttm/Desktop/tests/ruby/root/config/data/test.xls"
File.dirname(__FILE__) is the anchor for your relative path. Simply define the relative path to the file you want and let Ruby do the rest.
"Relative path to your project directory" talks about relative pathing in Ruby.
The answer to your question is going to be specific to the code that you are trying to use in your hooks.rb. If you could post a sample of what code you are using for this from your hooks.rb, that would be great. But the answer to your question is likely going to be some combination of the following:
File.join(File.dirname(__FILE__), '../../')
Where the first parameter is your current directory (root\features\support) and the second parameter is going to be the relative path to your root directory ('../../').
I've encountered a bug I can't seem to find any logic behind. I have this File object, which is created like this:
File file = new File("utilities/data/someTextFile.txt");
I then do file.exists(), and it returns false (!?). If the file is not found, I'm logging f.getAbsolutePath() to a file. When I look at the path, it seems OK. I can copy-paste the complete path into the "Run"-window in Windows and the file opens fine.
The file exists at all times and is not deleted nor changed during the running of my application. It is located at the local machine.
This only seems to occur in certain situations. I can reproduce the fault at any time, but I'm sure the path of the file object is not changed by the actions I make to reproduce the fault.
What can cause file.exists() to return false? Does this have something to do with permissions or file locks, etc.?
I am seeing the following situation on Windows 7:
file.exists() == false
file.getAbsoluteFile().exists() == true
The file in question is "var\log", the absolute path does refer to an existing file that is in a normal subdirectory (not a virtual store). This is seen from the IDE.
It seems like there is a difference on how the path is specified in Java.
For example, if the file path is specified as file:/C:/DEV/test.txt then
File f = new File(filename);
f.exists();
will return false. The path might work in the explorer or in the browser, but it is a URL and not absolute file path.
But on the other hand if the file path is specified as C:/DEV/test.txt then
File f = new File(filename);
f.exists();
will return true because the path is not a URL, but it is a absolute path.
With Spring Framework that is exactly what ResourceUtils.getFile(filename) does - where name can be either a URL or the absolute file path.
If the process does not have permissions to tell whether a file exists it will return false. It may be possible to open a file, but not tell by normal methods if it exists.
The above answers didn't help out in my case. As stated above, I had:
file.exists() => false
file.getAbsoluteFile().exists => true
The root cause for this was that the Windows 7 machine owner had modified the registry for CMD so that it would autorun a command to launch in a specific directory to work with Python. This modification crippled the Java 1.6 code which apparently uses CMD on Windows for certain file operations, such as exists(). Eliminating the autorun from the registry solved the issue.
When ["Hide extensions for known file types."] is checked windows open "t.txt.txt" when type "t.txt" in [explorer]/[run windows] but programmatically not.
Obviously there are a number of possible causes and the previous answers document them well, but here's how I solved this for in one particular case:
A student of mine had this problem and I nearly tore my hair out trying to figure it out. It turned out that the file didn't exist, even though it looked like it did. The problem was that Windows 7 was configured to "Hide file extensions for known file types." This means that if file appears to have the name "data.txt" its actual filename is "data.txt.txt".
Hope this helps others save themselves some hair.
If you don't want to deal with getAbsoluteFile() calls each time you have to call a method, you better create your file instance already with an absolute path. This should do the trick:
File file = new File("utilities/data/someTextFile.txt").getAbsoluteFile();
I suggest to surround it with a try-catch block, BTW.
The new File command just creates an instance of a file using the given path name. It doesn't actually create a file on the hard drive.
If you say
File file = new File ("path");
file.exists()
This can return true only if there was an existing file with the same path. If you intended to check for the same file declared in the first line, you may need to use it this way.
File file = new File ("path");
file.createNewFile();
file.exists();
Now this will return true.
To generalize the issue the problem arises while converting URL/URI to local paths.
Example: URL url = file:/D:/code%20repo%20sample/sample.txt
// To remove url reference
String localPath = url.getPath();
> /D:/code%20repo%20sample/sample.txt
// Decoding reserved characters in url from hexadecimal to character
URLDecoder.decode(localPath, StandardCharsets.UTF_8.toString());
> /D:/code repo sample/sample.txt
Hope this helps.
In my case
file save in
filepath = Environment.getExternalStorageDirectory().getAbsolutePath()+ "/VRSI/Audio/"+encrypted_filename+".mp3";
It is stored in in
/storage/emulated/0/VRSI/Audio/82B0999F16251F0DFE849F380D6AAEEA.mp3
it when when I get the file path is
/storage/emulated/0/Android/data/com.numerotec.vrsi/files/VRSI/Audio/AF7DC6C0C0B3EF3529EC70DAEF2324E0.mp3
So I replace the the string "Android/data/com.numerotec.vrsi/files/" as empty
after that
if (file.getAbsoluteFile().exists())
{
// write your code
}
is working fine
Good responses everyone. I've found this seems to be a problem with Java accessing the root C: directory on Windows. Any other directory should be fine, but for some reason, specifically mentioning C:\ or C: or C:/ might give an error. I have resolved this very similar problem by trapping mention to new File("C:"); and replacing it with new File(System.getProperty("file.separator")); or you should be able to hard code "\" instead of saying "c:" as your file directory and it might work out. Not elegant, but got the job done for me on this project.
I hope it helps. Might not be the right solution, but at least it worked for me. I'm on JRE 1.6, Win 7. Cheers!
Respectfully,
#Carpenter1010
If the situations where it fails involves running it as another user, and you're on Windows Vista/Windows 7, it could be caused by VirtualStore, the mechanism where Windows let an unprivileged user "write" places it normally cannot. The changes are however stored in "%USERPROFILE%\AppData\Local\VirtualStore\" which are private to each user account.
When nothing from above worked for me, I tried
filePath = filePath.trim();
This will clean your string from any unwanted charachter
FWIW, there is another place that this happens.
File("") is the name of the current directory. File("").exists() will usually return false. The File(("").getAbsoluteFile().exists() trick works and will return true (presuming the current directory exists...)
My suggestion is to attempt to read the file.
By doing so, i was able to get this error, that showed me that some weird characters had been prepended to my path.
java.nio.file.NoSuchFileException: ‪/home/rasp2/MyProjects/mapping.txt
In my IDE this was the path i was seeing:
Path path = Paths.get("/home/rasp2/MyProjects/mapping.txt");
So... i really don't know how, but these characters ‪ got into the way.
By deleting the path in the IDE and recreating it, i was able to get Files.exists(path) == true
I lately came across this same issue. What l did was to uninstall Netbeans, deleted netbeans folder from C drive, program files, update, programData, virtually everywhere. Then reinstall. Is now working fine.
Don't forget to backup up netbeans project folder before taken the actions above.
Hope it helps.
With some IDE(may be) and or with some OS(ex: window), by default they don't have write access on files. So if you try to do file.exists() it will show you false. in order to fix this, do like below
if your ref variable for File is f, example: File f = new File("path");
so in order to make it work , select f by mouse and then go to Search menu > Write access>Workspace. Hopefully it will work.
I think you should use backslash instead , like this:
File file = new File("C:\\User\\utilities\\data\\someTextFile.txt");
(two backslashes , not a typo )
Should solve the problem :)