I decided to test the file creating possibilities Java has to offer:
I tried to make a program that creates a file on a systems desktop.
To get the location, I did the following:
String targetLoc = System.getProperties("user.home") + "/Desktop"; //Returns /Users/targetUser/Desktop
And to then create the file:
File file = new File(targetLoc + "/testfile.txt"); //I'm aware of the slash before the name :)
try{
file.createNewFile();
}catch(Exception exception){
exception.printStackTrace();
}
And even though I don't see any errors above, I get the InvalidPathException.
Why would I get that error?
StackTrace On Request:
java.io.IOException: No such file or directory
at java.io.UnixFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:883)
at com.Code0.FileCreater.Main.MainFF.main(MainFF.java:41)
Answer:
It was a simple screw-up where I assigned the wrong value to the home String variable.
It was a simple screw-up where I assigned the wrong value to the home String variable.
Thank all of you very much for your support.
Regards,
Code0
Related
I've created a simple program that would write a file with a directory using the following codes:
String nameProve = nameField.getText();
String employee = ("C:\\Users\\ALLEN\\workspace32bit\\RETRIEVE_CHECKER1\\RETRIEVE_CHECKED1" + nameProve + ".txt");
PrintWriter outputStream1 = null;
try
{
outputStream1 = new PrintWriter(employeeName);
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, "Can not write to " + employeeName);
System.exit(0);
}
outputStream1.println("Employee Retrieve Executed");
outputStream1.close();
I've already exported my code to a .jar file and my code works just fine if i execute it in the computer were I've develop my program but when I copied the jar file to other computer and I also created the forlder (manually) that corresponds with the directory in my codes my program doesn't work and my catch block will show the message Can not write to "C:\Users\ALLEN\workspace32bit\RETRIEVE_CHECKER1\RETRIEVE_CHECKED1" + nameProve + ".txt"
Can anybody give me some advice on how to solve this error? Thanks!
Obviously you are the user ALLEN on your machine and run the program as that user, so everithing works fine, because you are the owner of the directory C:\Users\ALLEN.
Then you copy the jar to another machine, where the user ALLEN does not exist and you are logged in as antoher user let's say his name is Bob and create that directory unter C:\Users. You may have noticed that you when you wanted to create that directory as the user Bob windows has warned you that you need admin priviledges in order to compleate this action.
Now you try to run your program with the user Bob who has access only to his own directory C:\Users\Bob and try to write to ALLEN's own directory. So what happens is that you get an IOException telling you access denied which is good so!
You should not attepmt to write to other users private direcotries, this is a security issue.
In your code when dealing with filesystem, never hard code absolute path, always use relative paths, or if you need to defined a direcotry where all the data needed yb you program should be located, then pass ist as argument.
The simplest to do, ist use the following and work with the current working directory
String employee = "RETRIEVE_CHECKER1\\RETRIEVE_CHECKED1" + nameProve + ".txt";
You need to create the directory RETRIEVE_CHECKER1 either by hand in location where you run the program, or better yet in your program using File#mkdir and use it like this:
File employee = new File(dir, "RETRIEVE_CHECKED1" + nameProve + ".txt");
PrintWriter outputStream1 = new PrintWriter(employeeName);
Exception you catch will have all details- like access denied, directory not exist, etc. Currently you loose exception data (message, stacktrace) when catching it.
Please do something like
Do not catch just java.lang.Exception. This is too wide- will catch possible NullPointerException and present misleading message '"Can not write to'. Catch only specific exception instead- ones that are actually thrown from try block. In your case, that will be java.io.FileNotFoundException
Do not loose exception details. Print it to the standard error log, or even better use loging framework
catch block that adresses those issues:
catch(FileNotFoundException e) {
JOptionPane.showMessageDialog(null, e.getMessage());
e.printStackTrace();
}
I am facing some problem to fix the right file path.
I have a configuration file and following is the entry in config.properties:
strMasterTestSuiteFilePath="D:\\KeywordDrivenFramework\\MasterTestSuiteFile.xls"
Then i tried to read this property as
Properties prop=new Properties();
prop.load("config.properties")
String strpath=prop.getProperty("strMasterTestSuiteFilePath")
Syso(strpath) //prints above path with single slash as D:\KeywordDrivenFramework\MasterTestSuiteFile.xls
//When i use the same var for File existance check it say not exists
File obj=new File(strpath)
if(obj.exists())
Syso("Exists....")
else
Syso("Does not exist....")
Why it is going to else block, even though the file exists at path?
How to overcome it?
I tried
String str= strpath.replaceAll("\","\\") //but i am getting some syntax error "The method replaceAll(String, String) in the type String is not applicable for the arguments (String)"
Can anyone help me how to overcome this?
Find the code which i am trying, where i am going wrong?
public void LoadMasterTestSuite()
{
String strGlobalConfigSettingFilePath=System.getProperty("user.dir")+"/src/GlobalConfigurationSettings.properties";
FileInputStream objFIS; //Variable to hold FileSystem Objet
File objFile; //Variable to hold File Object
try
{
objFIS = new FileInputStream(new File(strGlobalConfigSettingFilePath));
globalObjProp.load(objFIS);
strMasterTSFilePath=globalObjProp.getProperty("strMasterTestSuiteFilePath");
objAppLog.info("Master Test Suite File Path configured as "+strMasterTSFilePath);
}catch (FileNotFoundException e)
{
objAppLog.info("Unable to find Global Configuration Settings File. So aborting...");
e.printStackTrace();
}catch (IOException e)
{
e.printStackTrace();
}
String str=strMasterTSFilePath.replace("\\", "\\\\");
objFile=new File(str);
System.out.println(str);
if(objFile.exists())
{
LoadTestSuite(strMasterTSFilePath);
}
else
{
objAppLog.info("Master Test Suite File not found at Path: "+strMasterTSFilePath);
System.exit(-1);
}
}
I guess what you wanted to do was:
String str= strpath.replaceAll("\\\\","\\")
\ is a special character in a String. To Treat it like a normal character, put another \ in front of it, so '\' actually is '\\'.
And for your case, I think you want to use .replace() and not .replaceAll().
When you debug, is strpath getting the correct path from the config file? I would also make sure that you're referencing the correct file path (paste the location into Windows Explorer and see if the file exists). If D:\ is a shared drive, use the actual server location.
Also, you can make sure that the extension of the Excel workbook is .xls and not .xlsx.
This question already has answers here:
File.createNewFile() thowing IOException No such file or directory
(10 answers)
Closed 1 year ago.
I am trying to create a file on the filesystem, but I keep getting this exception:
java.io.IOException: No such file or directory
I have an existing directory, and I am trying to write a file to that directory.
// I have also tried this below, but get same error
// new File(System.getProperty("user.home") + "/.foo/bar/" + fileName);
File f = new File(System.getProperty("user.home") + "/.foo/bar/", fileName);
if (f.exists() && !f.canWrite())
throw new IOException("Kan ikke skrive til filsystemet " + f.getAbsolutePath());
if (!f.isFile()) {
f.createNewFile(); // Exception here
} else {
f.setLastModified(System.currentTimeMillis());
}
Getting exception:
java.io.IOException: No such file or directory
at java.io.UnixFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:883)`
I have write permission to the path, however the file isn't created.
If the directory ../.foo/bar/ doesn't exist, you can't create a file there, so make sure you create the directory first.
Try something like this:
File f = new File("somedirname1/somedirname2/somefilename");
if (!f.getParentFile().exists())
f.getParentFile().mkdirs();
if (!f.exists())
f.createNewFile();
Print the full file name out or step through in a debugger. When I get confused by errors like this, it means that my assumptions and expectations don't match reality. Make sure you can see what the path is; it'll help you figure out where you've gone wrong.
Be careful with permissions, it is problably you don't have some of them. You can see it in settings -> apps -> name of the application -> permissions -> active if not.
Try with
f.mkdirs() then createNewFile()
You may want to use Apache Commons IO's FileUtils.openOutputStream(File) method. It has good Exception messages when something went wrong and also creates necessary parent dirs. If everything was right then you directly get your OutputStream - very neat.
If you just want to touch the file then use FileUtils.touch(File) instead.
File.isFile() is false if the file / directory does not exist, so you can't use it to test whether you're trying to create a directory. But that's not the first issue here.
The issue is that the intermediate directories don't exist. You want to call f.mkdirs() first.
I got the same problem when using rest-easy. After searching while i figured that this error occured when there is no place to keep temporary files. So in tomcat you can just create tomcat-root/temp folder.
i fixed my problem by this code on linux file system
if (!file.exists())
Files.createFile(file.toPath());
Does anyone have an experience or know when the method File.getCanonicalPath() will throw an IOException
I have tried to look up from the Internet and the best answer is in File API which says
"IOException - If an I/O error occurs, which is possible because the construction of the canonical pathname may require filesystem queries"
However, it is not clear to me because I still cannot think of a case which this might fail. Can anyone give me concrete examples which can happen on Linux, Windows and other OS (optional)?
I reason I want to know is because I want to handle this exception accordingly. Thus, it will be best if I know all the possible failures that can happen.
Here is a Windows example:
Try calling getCanonicalFile on a file in your CD-drive, but without a CD loaded. For example:
new File("D:\\dummy.txt").getCanonicalFile();
you will get:
Exception in thread "main" java.io.IOException: The device is not ready
at java.io.WinNTFileSystem.canonicalize0(Native Method)
at java.io.Win32FileSystem.canonicalize(Win32FileSystem.java:396)
at java.io.File.getCanonicalPath(File.java:559)
at java.io.File.getCanonicalFile(File.java:583)
The IO Exception also occurs if we try creating a File object with Windows device file keywords (see device files) used as file name.
As if you try renaming the file to those keywords, Windows will not let you to make it (no CON, PRN, COM1 etc. file names allowed), Java also won't be able to convert that file name to the correct path.
So, any of next next code will trow the IO Exception:
File file = new File("COM1").getContextPath();
File file = new File("COM1.txt").getContextPath();
File file = new File("C:/somefolder/COM1.txt").getContextPath();
However, next code should work:
File file = new File("COM1_.txt").getContextPath(); //underscore wins :)
Here is generic example for all OS:
new File("\u0000").getCanonicalFile();
Before canonicalizing of the file, its validity is checked with java.io.File#isInvalid:
final boolean isInvalid() {
if (status == null) {
status = (this.path.indexOf('\u0000') < 0) ? PathStatus.CHECKED
: PathStatus.INVALID;
}
return status == PathStatus.INVALID;
}
And if the file is invalid - you'll get an IO exception:
public String getCanonicalPath() throws IOException {
if (isInvalid()) {
throw new IOException("Invalid file path");
}
return fs.canonicalize(fs.resolve(this));
}
Profit!
Seen here in the Sun Bug Database.
For JRE 1.4.2_06, File.getCanonicalPath() wasn't working on Windows for a removable drive when there is no media present in the drive.
It was corrected in Java 1.5, but you can see there can be OS-based problems with this method.
I don't know of any problem in the current time, but it can happen, that's exactly what the Javadoc says. Usually it's quickly fixed in the newest Java version.
One more scenario, When you try to use Operating System restricted/invalid characters as your file name.
For Windows \ / : * ? " < > | these are the invalid characters. Try to rename a file with : you will get a balloon/tip message about the invalid characters.
Try the Following Java Code.
File file = new File("c:/outputlog-2013-09-20-22:15");
//A common scenario when you try to append java.util.Date to create a file like
//File newFile = new File(filename + "_" + new Date());
System.out.println(file.getAbsolutePath());
System.out.println(file.getCanonicalPath());
If the File name contains
* ? you will get java.io.IOException: Invalid argument
| : you will get java.io.IOException: The filename, directory name, or volume label syntax is incorrect
when you use the getCanonicalPath() method. If we use any of " < >
char in the file name, then getCanonicalPath() method is not failing but when you try to create the file you will be getting the Invalid argument Exception.
Refer jdk7 api
The precise definition of canonical form is system-dependent. Here I have used windows 7.
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.