I know the same question has been asked many many times, but going through all the answers already posted I couldn't find a solution.
First of all here's the code I'm using to test the issue after i encountered it in my project :
InputStream test;
System.out.println(this.getClass());
System.out.println(("classpath is: " + System.getProperty("java.class.path")));
test = getClass().getResourceAsStream("/pairs/images/100/back/back1.png");
if (test == null)
{
System.out.println("getClass().getResourceAsStream(\"/pairs/images/100/back/back1.png\") is null");
test = GridPanel.class.getClassLoader().getResourceAsStream("pairs/images/100/back/back1.png");
}
if (test == null)
{
System.out.println("GridPanel.class.getClassLoader().getResourceAsStream(\"pairs/images/100/back/back1.png\") is null");
test = ClassLoader.getSystemClassLoader().getResourceAsStream("pairs/images/100/back/back1.png");
}
if (test == null)
{
System.out.println("ClassLoader.getSystemClassLoader().getResourceAsStream(\"pairs/images/100/back/back1.png\") is null");
Thread.currentThread().getContextClassLoader().getResourceAsStream("pairs/images/100/back/back1.png");
}
if (test == null)
System.out.println("Thread.currentThread().getContextClassLoader().getResourceAsStream(\"pairs/images/100/back/back1.png\") is null");
So as per title everyone of these calls to getResourceAsStream() returns null, but only when executin the jar file, when launching inside the IDE (Netbeans 8.0.2) they all return the correct stream (tested individually not with this piece of code) and I can work with it.
The jar file contents are as follow:
While the src folder in the netbeans project folder is the following:
So I'm really baffled at the moment, I've tried using the default settings when building with netbeans but I'm losing my head around this issue.
Any hints or ideas would be much appreciated!
I think the getResourceAsStream is not reading from filesystem, the leading slash will try to read from the root of the classpath (if you add a directory will read from the root). If you don't put the leading slash, you will read from the package the class is from.
Did you add the directory/subdirectories you want to read the file from in the classpath?
TL;DR It was due some stupid issue with NTFS permission, moving the jar made it work
So I feel very stupid right now...
I tried running it in a Linux environment and everything worked as supposed.
Each one of those calls was returning a non-null InputStream pointing to the resource.
So I did something very simple: just moved around the compiled jar in Windows to check if it had something to do with NTFS permissions (keep in mind that I'm using an administrator account and I can freely write, read and execute in those folders).
Moving it to the root of the project didn't work, but moving it on the desktop WORKED.
What amazes me more is that in some other parts of the projects I'm doing
URL jarUrl = PairsDeck.class.getProtectionDomain().getCodeSource().getLocation();
to read the whole content of the jar file and that works every time even in the old directory, so that's why I hadn't thought of screwed permissions since the beginning (and I was launching it from a command prompt with admin privileges).
So I guess somehow the program can read its jar with that call but not load resources from it inside my netbeans project folder due to some issues with NTFS permissions.
To add some confusion
File file = new File(jarUrl.toURI());
file.canWrite();
file.canRead();
file.canExecute();
all of the above return true.
I'm just curious to know if there was a way to understand better the issue and maybe have a way to signal some permissions error from the java code.
Thanks wholeheartedly to everybody involved for the help!
There are two problems here.
Windows is case-insensitive. Other platforms and inside a jar names are case-sensitive.
The getClass() class determines in which jar/class path the resource is souught. Especially a unit test will not be put in a jar, or a child class might be located outside the jar. Either use a SomeClassInJar.class or use a ClassLoader which searches over all jars/class paths. A class loader uses only absolute paths, and you must not start the path with a /.
I have a folder called WalnutiQ. Inside this folder is is a file at WalnutiQ/train/model/MARK_II/Save.java
Save.java
JsonFileInputOutput.saveObjectToTextFile(myObjectJson,
"Digits.txt");
which works! However, the file Digits.txt is unfortunately saved in WalnutiQ/Digits.txt
How do I save the file Digits.txt at WalnutiQ/train/model/MARK_II/Digits.txt???
I am programming in java in eclipse in windows. I have tried
JsonFileInputOutput.saveObjectToTextFile(myObjectJson,
"/train/model/MARK_II/Digits.txt");
JsonFileInputOutput.saveObjectToTextFile(myObjectJson,
"\\train\\model\\MARK_II\\Digits.txt");
but neither work.
judging from the result you are getting your current directory is pointed at WalnutIQ. You might try using .\train\model\MARK_II\Digits.txt. Windows treats the . (period) as a token for "current directory". Your other attempt would have tried to find the train directory in the root of C because the \ (backslash) is a token for the root (c:). It likely fails because that folder does not exist - unless it created it... might go look :) I don't use Json in eclipse which is why I'm not answer your question with code.
Have you considered using the full absolute file path to the text file, rather than the relative one you are currently using? This may not be practical, depending on how you plan on using your program, but it might be worth a shot.
Depending on how the library saves files (I imagine it's using File behind the scenes), you should be able to supply an absolute path to the location you want it to save to.
JsonFileInputOutput.saveObjectToTextFile(myObjectJson,
"/path/to/WalnutiQ/train/model/MARK_II/Digits.txt");
Please see code snippet:
File[] additionalFiles = new File(FILE_PATH).listFiles();
boolean isDirectory = file.isDirectory();
I have verified that the directory path is correct, and when I run the code on Windows, the value of isDirectory is true (as it should be). Any suggestions as to why this occurs on Linux (RedHat Enterprise Linux)?
Symlinks don't read as directories, if I remember correctly. The right way around that is:
new File(FILE_PATH).getCanonicalFile().isDirectory();
(NOTE: Untested, I don't have a linux box to test this on easily).
I experienced this issue once. My case is so funny, I was reading the path from a properties file and that path contained a tab character at the end of the string. That was the reason why the path wasn't recognized as a directory
Checkout this link
http://bugs.sun.com/view_bug.do;jsessionid=56e03cb783aaf9725daf5ec8d8?bug_id=6539692
You may have this issue.
Otherwise I would guess an issue with file permissions (though that might throw back security exception and I am assuming your code does not wrap it and return false) or may be a sym link issue that I dont know much about.
I am working on a small basic GUI program that gets the files from my resources and gets the names of the files and places them in a combo box. for example i just have a file inside the same package called images and trying to get the files names. the way I get the file is by using the getResoure() like so
java.net.URL url = FileDemo.class.getResource("images");
but when I try to get the files inside the directory
File urlfile = new File(url.toString());
String[] files = urlfile.list();
the first line will convert the url to string and create a file object but when I try to get the list of files inside the directory it returns a null to the array of strings.
I broke down the code and used the debugger in netbeans found out, when it did the SecurityManager check it wouldn't pass.
My question is are the files inside the project protected or there is no way to access them using the list() and listFiles() or am i doing something wrong? Also I ran the same script on my schools computer which they have windows 7 the code above worked. But when i ran it on my mac and even 2 win xp machines it just didn't work? why is that ?
I hope this makes sense i am just stuck here still a new to java
Thanks in Advance.
The class to getResource(String) is returning a URL to images but there's no guarantee that this is a file URL (beginning "file:"). If your class is embedded within a jar file this certainly won't be the case, hence why it fails in some situations and not others.
If your intention here is to actually make a portion of a file system visible to the user then I'd recommend avoiding getResource altogether, which is typically more useful when your application wishes to locate and load resources such as icons or config files.
Instead, you could use JFileChooser, which is a rich Swing component for navigating the file system and selecting files.
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 :)