java Failed to create new file in windows 7? - java

I 'm trying to create new file in windows 7 using
file.createNewFile()
but the file is not created and I got the following exception
Message:
The system cannot find the path specified
Stack Trace:
[java.io.IOException: The system cannot find the path specified,
at java.io.WinNTFileSystem.createFileExclusively(Native Method),
at java.io.File.createNewFile(File.java:883),
at com.mercury.mtf.actions.file.CreateEmptyFileTask.execute(CreateEmptyFileTask.java:56),
at com.mercury.mtf.actions.file.CreateEmptyFileAction.execute(CreateEmptyFileAction.java:42),
at com.mercury.mtf.core.AbstractAction.run(AbstractAction.java:50),
at com.mercury.mtf.core.Unit.runUnitAction(Unit.java:347),
at com.mercury.mtf.core.Unit.executeUnitAction(Unit.java:176),
at com.mercury.mtf.core.Unit.run(Unit.java:121),
at com.mercury.mtf.core.execution.DefaultUnitExecutor.call(DefaultUnitExecutor.java:24),
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303),
at java.util.concurrent.FutureTask.run(FutureTask.java:138),
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:98),
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:207),
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886),
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908),
at java.lang.Thread.run(Thread.java:619)]
I'm sure that the path exists, but I realized that the folder marked as read only. I tried to remove the read only flag but I can't get this to work.

Make sure your path separator character is proper.. You can use single forward slash or double back slashes. For example,
File f = new File("C:\\Documents and Settings\\thandasoru\\My Documents\\temp.txt");
f.createNewFile();

If the file is temporary you can use this function and you can forget all permissions problems:
File.createTempFile("prefix", "suffix")

Use File newFile=new File(folderName+chipItems[i]); rather than using File newFile=new File(folderName+chipItems[i], "w");. That will be OK. Avoid File Mode when you like to give functionality like Unix touch command.

Related

URI to file in Zip incorrect if path contains spaces

I want to get the URIs to the entries of a zip file in order to keep references to it's contents without having to keep the zip file open.
Therefore I open the zip file using the zip filesystem and export the Path of the entries as URI.
Path zipfile = ...
URI uriOfFileInZip;
try(FileSystem fs = FileSystems.newFileSystem(zipfile, null)){
Path fileInZip = fs.getPath("fileInZip.txt");
uriOfFileInZip = fileInZip.toUri();
}
Now I want to read the file again, so I try to open a stream to the file.
InputStream is = uriOfFileInZip.toURL().openStream();
This works as long as the path of the zip file does not contain any spaces. As soon as it contains spaces, I get an error like this
java.io.FileNotFoundException: D:\example\name%20of%20zipfile.zip (The system cannot find the file specified)
the URI to the file in the zip is
jar:file:///D:/example/name%2520of%2520zipfile.zip!/fileInZip.txt
the name of the zip is
D:\example\name of zipfile.zip
I wonder about the %2520 this seems like an issue with the URL encoding, but shouldn't this be handled transparently? Or is it a bug?
Any ideas to solve this problem?
Looks like a bug.
Seems as if com.sun.nio.zipfs.ZipPath.toUri() is either messed up, or I didn't read the corresponding RFC yet ;-). Played around with some other file names. There seems to be a double encoding going on for the zip file path, but not for the file entry in the zip.
Besides not using the URI-approach you could also build the URI yourself from scratch, but then you are not that flexible anymore. Or you just undo the unnecessary encoding:
String uriParts[] = uriOfFileInZip.toString().split("!");
uriParts[0] = URLDecoder.decode(uriParts[0], "UTF-8");
uriOfFileInZip = URI.create(String.join("!", uriParts));
But to be honest, I would rather try to omit the URI for zip files or if you really have to, rename the files beforehand ;-) Better yet: open a bug if it does not behave as stated in the corresponding RFCs.
You may also want to get some additional information from the following question regarding bug, etc.:
Java 7 zip file system provider doesn't seem to accept spaces in URI
EDIT (added proposal without URI):
You can also try to completely work with your Path instance (fileInZip) instead of the URI, as the path instance "knows" its filesystem.
As soon as you need access to the file inside the zip, you create a new FileSystem based on the information of the Path instance (fileInZip.getFileSystem()). I did not elaborate that completely, but at least the file store should contain all the necessary information to access the zip file again. With that information you could call something like FileSystems.newFileSystem(Paths.get(fileStoreName), null).
Then you can also use Files.newInputStream(fileInZip) to create your InputStream. No need to use URI here.
This is only reproducible with JDK 8. The later versions do not have this issue.
For the following code:
Map<String, String> env = new HashMap<>();
env.put("create", "true");
final FileSystem fs = FileSystems.newFileSystem(new URI("jar:file:/D:/path%20with%20spaces/junit-4.5.jar"), env);
System.out.println(fs.getPath("LICENSE.TXT").toUri()); `
I got the following output with JDK 1.8.0_212 :
jar:file:///D:/path%2520with%2520spaces/junit-4.5.jar!/LICENSE.TXT
whereas with JDK 11.0.3:
jar:file:///D:/path%20with%20spaces/junit-4.5.jar!/LICENSE.TXT
A search through the Java bug system shows that it had been fixed in JDK 9 with JDK-8131067 .

How to get the right file path in Servlet program?

I am trying to read xml and txt file using relative path,
I tried getServletContext().getContextPath();
but it gets the path in a wrong way
for example
My file path is :
D:\dev\workspace\Simulater\src\resources\Map.xml
Now when I apply,
System.out.println(getServletContext().getContextPath());
I get as an output:
/Simulater
and when i apply :
File myTestFile= new File(Api.CONTEXT_PATH+fileName);
String path = myTestFile.getAbsoluteFile().toString();
System.out.println(path);
i get D:\Simulater\src\resources\Map.xml
an it is a wrong path since it dose not contains
:\dev\workspace\
it seams like java takes the project name and add the driver that contains it
so dose any one can provide any help to get the right path
thanx
use getServletContext().getRealPath("/") to get full path D:\dev\workspace\Simulater\src\resources\ then you can read file by giving this full path and file name.
To read a file you nead to open an InputStream, as your file is in your classpath you can open the stream with the following statement :
InputStream is = this.getClass().getResourceAsStream("/Map.xml");

Can I use File.createTempFile() to create a file with a non-random name

I want to create a temporary file (that goes away when the application closes) with a specific name. I'm using this code:
f = File.createTempFile("tmp", ".txt", new File("D:/"));
This creates something like D:\tmp4501156806082176909.txt. I want just D:\tmp.txt. How can I do this?
In this case, don't use createTempFile. The point of createTempFile is to generate the "garbage" name in order to avoid name colisions.
You should use File.createNewFile() or simply write to the file. Whichever is more appropriate for your use case. You can then call File.deleteOnExit() to get the VM to look after cleaning up the file.
If you want to create just tmp.txt, then just create the file using createNewFile(), instead of createTempFile(). createTempFile is used to create temporary files that should not have the same name when created over and over.
Also have a look at this post which shows a very simple way to create files.
Taken the post mentioned above:
String path = "C:"+File.separator+"hello"+File.separator+"hi.txt";
//(use relative path for Unix systems)
File f = new File(path);
//(works for both Windows and Linux)
f.mkdirs();
f.createNewFile();
try regex
fileName = fileName.replaceAll("\\d", "");

FileInputStream and FileNotFound Exception

I am trying to retrieve a jrxml file in a relative path using the following java code:
String jasperFileName = "/web/WEB-INF/reports/MemberOrderListReport.jrxml";
File report = new File(jasperFileName);
FileInputStream fis = new FileInputStream(report);
However, most probably I didn't succeed in defining the relative path and get an java.io.FileNotFoundException: error during the execution.
Since I am not so experienced in Java I/O operations, I didn't solve my problem. Any helps or ideas are welcomed.
You're trying to treat the jrxml file as an object on the file-system, but that's not applicable inside a web application.
You don't know how or where your application will be deployed, so you can't point a File at it.
Instead you want to use getResourceAsStream from the ServletContext. Something like:
String resourceName = "/WEB-INF/reports/MemberOrderListReport.jrxml"
InputStream is = getServletContext().getResourceAsStream(resourceName);
is what you're after.
You should place 'MemberOrderListReport.jrxml' in classpath, such as it being included in a jar placed in web-inf\lib or as a file in web-inf\classes.
The you can read the file using the following code:
InputStream is=YourClass.class.getClassLoader().getResourceAsStream("MemberOrderListReport.jrxml");
String jasperFileName = "/web/WEB-INF/reports/MemberOrderListReport.jrxml";
Simple. You don't have a /web/WEB-INF/reports/MemoberOrderListReport.jrxml file on your computer.
You are clearly executing in a web-app environment and expecting the system to automatically resolve that in the context of the web-app container. It doesn't. That's what getRealPath() and friends are for.
check that your relative base path is that one you think is:
File f = new File("test.txt");
System.out.println(f.getAbsoluteFile());
I've seen this kind of problem many times, and the answer is always the same...
The problem is the file path isn't what you think it is. To figure it out, simply add this line after creating the File:
System.out.println(report.getAbsolutePath());
Look at the output and you immediately see what the problem is.

Cannot make file java.io.IOException: No such file or directory [duplicate]

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());

Categories

Resources