File not found exception in java - java

I have done this:
File inputPropertiesFile = new File("/Users/adrian/Documents/workspace/Ronan/src/watermarker/test");
InputStream propertiesStream = new FileInputStream(inputPropertiesFile);
but I get this exception:
java.io.FileNotFoundException: /Users/adrian/Documents/workspace/Ronan/src/watermarker/test (No such file or directory) at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.<init>(FileInputStream.java:120)
But the file is at that location fooor suure.And is not empty.What is wrong there?
Thank you

Maybe you can check if the File is accessible for the Program?
If the File is not accessible, it also cannot be found and hence raises this exception.

Yeah, if you try using /Users/adrian in explorer, you won't get to that path. If you use C:/Users/adrian, you will. I'm sure java is having the same problem

Is the file readable by your process? Try changing its permissions
chmod 777 thefile
and rerunning. If that works, then you know its a permissions issue. changing the permissions like that is probably not a permanent solution, and can be a security risk if you are on a multi-user system. But that's a different problem...

On Windows? Maybe you run your code on D: instead C:. If so put full path "c:\Users\adrian..."
It looks like default path to Eclipse workspace on Win7. If so, I have no "/Documents/" in the path. I have "/Users/myname/workspace/projectName/src....".

surround it by a try-catch block
try {
inputStream = new FileInputStream(propertiesFile);
prop.load(inputStream);
} catch (FileNotFoundException e1) {
getLog().error(e1);
} catch (IOException e) {
getLog().error(e);
}

Related

Path on Ubuntu server in java?

I just did a little project in java, packed the .jar and application.properties to my VPS and wanted to test it there. The tool reads logfiles.
I specified the path to the logfile within the application.properties as follows:
LOGPATH=/folder1/folder2/logs/thelogIwant.log
The path is parsed as follows:
public String makePath(String path) {
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream("application.properties");
prop.load(input);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return prop.getProperty(path);
}
Path logFile = Paths.get(makePath("LOGPATH"));
It even seems to to this right, as the ErrorMessage states:
SEVERE: /folder1/folder2/logs/thelogIwant.log (No such file or directory)
The logfile is being created by another application and therefore in another directory than the .jar I am running.
The path exists on my VPS and I can navigate to and through it.
Can someone point me in the right direction? What's going wrong here?
Things I tried:
Specify path with "~/folder1/..."
Specify path with "folder1/..."
I can think of a few possible explanations:
The pathname in your config file is wrong; e.g. there is a typo or some other discrepancy that you didn't notice.
You are loading a different property file to the one that you think.
There is a mismatch between the property name in the file and the name that your tool uses.
The other application didn't create the log file
Permissions: your tool may be running as a user that isn't permitted to read one of the directories on the path.
SELinux in enforcing mode can prevent an application (e.g. running as a service) from accessing files.
Homoglyphs, either in the property file1, your source code or the name of the file in the file system.
The things that you tried are unlikely to work. A correct absolute pathname is more robust than a relative pathname, and Paths.get doesn't know how to deal with ~. (The expansion of ~ is a shell feature ....)
I would try this:
Modify your tool to output the value of the "LOGPATH" property ... enclosed in quote characters so that you can see any spurious whitespace characters at the beginning / end of the value.
Run the tool.
Using copy-and-paste, see if you can open the file using exactly the pathname that your tool uses.
In short, verify that the pathname you are actually using is what you expect it to be.
1 - In practice, classic format property files are encoded in LATIN-1, so this is impossible.
I was able to fix this, thanks #Steven for your help!
I used the pwd command when in the directory the files are in and recognized that the true absolute path starts with /home/myusername/folder1/...
Works fine now.

java.io.FileNotFoundException (Access is denied) - file.canWrite() does not working

I'm trying to empty a jasper file. Before write, I checked it for write access and I t gives me that I can write on it. But it terminates with java.io.FileNotFoundException (Access is denied) - file.canWrite()
What am I missing?
try {
File f = new File("C:\\Program Files (x86)\\XXXXXX\\XXX\\X\\X.jrxml");
if(f.canWrite()){
BufferedWriter bf = new BufferedWriter(new FileWriter(f));
bf.write("");
bf.close();
}
} catch (Exception e) {
e.printStackTrace();
}
Writing in your Program Files folder often has quite restricted access, and you must be on an Administrator account to do so usually. I would suggest you try saving your .jrxml in a more accessible directory outside \\Program Files (x86) like your ApplicationData folder, it may even already be there. You can also try something like Isolated Storage to ensure you have permissions, this should show you how to use it.
Apparently, canWrite may return true even if you cannot write on windows (according to this : http://bugs.java.com/bugdatabase/view_bug.do?bug_id=8060110). The javadoc is not really clear about that.
You can try using Files.isWritable if you are using at least java 7 to see if you have the expected result. Otherwise, it seems that the only way to check the rights is to try writing and see what happens.

java.io.FileNotFoundException, file not being found

I just wanted to read a file line by line.
This was meant to be simple, but i just can't get it right!
String fileName = "C:/Users/Diogo/Desktop/Krs_Grafo/Graph.txt";
FileReader file = new FileReader(fileName);
BufferedReader inputStream = new BufferedReader(file);
System.out.println(inputStream.readLine());
i keep getting the error:
Exception in thread "main" java.io.FileNotFoundException: C:\Users\Diogo\Desktop\Krs_Grafo\Graph.txt (O sistema não pode encontrar o arquivo especificado)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:120)
at java.io.FileInputStream.<init>(FileInputStream.java:79)
at java.io.FileReader.<init>(FileReader.java:41)
at krs_grafo.Krs_Grafo.main(Krs_Grafo.java:51)
Java Result: 1
The system cant find the file, but i'm sure as hell it is there!
I'm using Netbeans 7.0 on a Windows 7.
Any suggestions?
AS SAID IN THE COMMENTS, it was searching for "Graph" and not "Graph.txt". This was from a previous execution where I tried without the extension. So, I edited it to be coherent. It still doesn't work.
The problem here is that the file name was actually "Graph.txt.txt" wich I couldn't see because the extensions were hidden.
Thanks to user "Michael Brewer-Davis" who asked in the comments for "output of cd and dir in the given directory".
Also point out that either / and \\ work just fine.
As JB Nizet points in a comment, the error message hints that the program tried to open a "Graph" file (not path and no extension), which is not compatible with the code you are showing us. Are you sure that that error message comes from running that code? Didi you try to debug it (step by step) ?
Windows 7? Perhaps you'd prefer to set up a working directory in some "nice" directory, like C:\wk\ or something like that, so that you can rule out permission problems and have nicer-shorter paths.
The suggestion of some answers about backlasshes is not relevant. Forward slashes work nice in Java in Windows. No need to worry about that.
You need to add the try catch block.
public static void main(String...args){
String fileName = "C:/Users/DY.Liu/Desktop/Krs_Grafo/Graph.txt";
try{
FileReader file = new FileReader(fileName);
BufferedReader inputStream = new BufferedReader(file);
System.out.println(inputStream.readLine());
} catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e){
}
}
I had a similar problem with a java.io.FileNotFoundException. I had downloaded a project from an e-mail, unzipped and stored on my Desktop, NOT my workspace which caused the FileNotFoundException.
To get the right path, I copied down the exact path from what was shown when I imported the project. and this fixed the problem for me.

Writing to a file, where is the output file?

FileWriter outFile = null;
try {
outFile = new FileWriter("member.txt");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.println("test");
Running that command, where is the member.txt ? I am using windows vista. UAC enabled so when I run it, I don't think it's writing to the txt file. txt file is created however, but it's empty.
Relative paths in Java IO are relative to current working directory. In Eclipse, that's usually the project root. You're also writing to out instead of outFile. Here's a minor rewrite:
File file = new File("member.txt");
FileWriter writer = null;
try {
writer = new FileWriter(file);
writer.write("test");
} catch (IOException e) {
e.printStackTrace(); // I'd rather declare method with throws IOException and omit this catch.
} finally {
if (writer != null) try { writer.close(); } catch (IOException ignore) {}
}
System.out.printf("File is located at %s%n", file.getAbsolutePath());
Closing is mandatory since it flushes the written data into the file and releases the file lock.
Needless to say that it's a poor practice to use relative paths in Java IO. If you can, rather make use of the classpath. ClassLoader#getResource(), getResourceAsStream() and so on.
If the file is successfully created (no exception is raised), it is in the current working directory.
For the Java class you're executing, right click on the file and go to "Run As -> Run Configurations..."
In this screen, go to the "Arguments" tab. At the bottom of the screen, look for the "Working directory" setting. This is the directory that your Java class will run from.
In your example, you're creating "member.txt" in the current directory, so it will show up in whatever location your "Working directory" is set to.
It depends on the IDE you're using also. It will usually go into the same directory that the file.java is located at. I think programs like Eclipse and Netbeans may toss it in a different directory.
If running from Eclipse, the current working directory will be your project's base directory (view your project properties to find that location on disk). You should be able to see the file in the Project Explorer by refreshing the project (click on the project and hit F5).
You can specify an alternative working directory from the Run Configurations dialog under the Arguments tab.

What are possible reasons for java.io.IOException: "The filename, directory name, or volume label syntax is incorrect"

I am trying to copy a file using the following code:
File targetFile = new File(targetPath + File.separator + filename);
...
targetFile.createNewFile();
fileInputStream = new FileInputStream(fileToCopy);
fileOutputStream = new FileOutputStream(targetFile);
byte[] buffer = new byte[64*1024];
int i = 0;
while((i = fileInputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, i);
}
For some users the targetFile.createNewFile results in this exception:
java.io.IOException: The filename, directory name, or volume label syntax is incorrect
at java.io.WinNTFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:850)
Filename and directory name seem to be correct. The directory targetPath is even checked for existence before the copy code is executed and the filename looks like this: AB_timestamp.xml
The user has write permissions to the targetPath and can copy the file without problems using the OS.
As I don't have access to a machine this happens on yet and can't reproduce the problem on my own machine I turn to you for hints on the reason for this exception.
This can occur when filename has timestamp with colons, eg. myfile_HH:mm:ss.csv Removing colons fixed the issue.
Try this, as it takes more care of adjusting directory separator characters in the path between targetPath and filename:
File targetFile = new File(targetPath, filename);
I just encountered the same problem. I think it has to something do with write access permission. I got the error while trying to write to c:\ but on changing to D:\ everything worked fine.
Apparently Java did not have permission to write to my System Drive (Running Windows 7 installed on C:)
Here is the test program I use
import java.io.File;
public class TestWrite {
public static void main(String[] args) {
if (args.length!=1) {
throw new IllegalArgumentException("Expected 1 argument: dir for tmp file");
}
try {
File.createTempFile("bla",".tmp",new File(args[0]));
} catch (Exception e) {
System.out.println("exception:"+e);
e.printStackTrace();
}
}
}
Try to create the file in a different directory - e.g. "C:\" after you made sure you have write access to that directory. If that works, the path name of the file is wrong.
Take a look at the comment in the Exception and try to vary all the elements in the path name of the file. Experiment. Draw conclusions.
Remove any special characters in the file/folder name in the complete path.
Do you check that the targetPath is a directory, or just that something exists with that name? (I know you say the user can copy it from the operating system, but maybe they're typing something else).
Does targetPath end with a File.separator already?
(It would help if you could log and tell us what the value of targetPath and filename are on a failing case)
Maybe the problem is that it is copying the file over the network, to a shared drive? I think java can have problems when writing files using NFS when the path is something like \mypc\myshared folder.
What is the path where this problem happens?
Try adding some logging to see exactly what is the name and path the file is trying to create, to ensure that the parent is well a directory.
In addition, you can also take a look at Channels instead of using a loop. ;-)
You say "for some users" - so it works for others? What is the difference here, are the users running different instances on different machines, or is this a server that services concurrent users?
If the latter, I'd say it is a concurrency bug somehow - two threads check try to create the file with WinNTFileSystem.createFileExclusively(Native Method) simultaniously.
Neither createNewFile or createFileExclusively are synchronized when I look at the OpenJDK source, so you may have to synchronize this block yourself.
Maybe the file already exists. It could be the case if your timestamp resolution is not good enough. As it is an IOException that you are getting, it might not be a permission issue (in which case you would get a SecurityException).
I would first check for file existence before trying to create the file and try to log what's happening.
Look at public boolean createNewFile() for more information on the method you are using.
As I was not able to reproduce the error on my own machine or get hands on the machine of the user where the code failed I waited until now to declare an accepted answer.
I changed the code to the following:
File parentFolder = new File(targetPath);
... do some checks on parentFolder here ...
File targetFile = new File(parentFolder, filename);
targetFile.createNewFile();
fileInputStream = new FileInputStream(fileToCopy);
fileOutputStream = new FileOutputStream(targetFile);
byte[] buffer = new byte[64*1024];
int i = 0;
while((i = fileInputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, i);
}
After that it worked for the user reporting the problem.
So it seems Alexanders answer did the trick - although I actually use a slightly different constructor than he gave, but along the same lines.
I yet have to talk that user into helping me verifying that the code change fixed the error (instead of him doing something differently) by running the old version again and checking if it still fails.
btw. logging was in place and the logged path seemed ok - sorry for not mentioning that. I took that for granted and found it unnecessarily complicated the code in the question.
Thanks for the helpful answers.
A very similar error:-
" ... java.io.IOException: The filename, directory name, or volume label syntax is incorrect"
was generated in Eclipse for me when the TOMCAT home setting had a training backslash.
The minor edit suggested at:-
http://www.coderanch.com/t/556633/Tomcat/java-io-IOException-filename-directory
fixed it for me.
FileUtils.copyFile(src,new File("C:\\Users\\daiva\\eclipse-workspace\\PracticeProgram\\Screenshot\\adi.png"));
Try to copy file like this.

Categories

Resources