I have been writing a program for batch system using quartz and i find a problem,
if(!file.renameTo(new File(PATH_FILE_PROCESSED+file.getName())))System.out.println("Cannot Move File :"+file.getAbsolutePath());
else{
if(!file.delete())System.out.println("Cannot Delete File :"+file.getAbsolutePath());
}
i want to move file from one directory to another directory but i can't delete the file in the same process, from my analysis i think the file haven't finished copying then running the file.delete();
my question is, is there a way to wait until the file finished copying then run the file.delete?
thanks
Renaming is almost instant as it doesn't copy the file, it just moves which directory it appears in (unless you are moving between filesystems)
On windows, you can't rename or delete if you have the file open somewhere. Make sure you have close()ed it properly.
i think i already found the problem, the problem is when i insert the the file inside zip some other code already insert the data so it create duplicate in database and it create an error like this. so thanks for answering the question
Related
I have a directory M:\SOURCE from which I have listed and moved it's contents until it is empty
After that, I want to go ahead and delete it, I have tried (yes I also made sure it was empty):
sourceFile being "M:\SOURCE"
sourceFile.delete()
Files.delete(sourceFile.toPath());
FileUtils.deleteQuietly(sourceFile);
FileUtils.deleteDirectory(sourceFile);
FileUtils.forceDelete(sourceFile)
There are no exceptions being thrown by any of the other methods and .delete() returns true
HOWEVER, the directory still exists and when trying to access the folder I get the following message from windows:
When running process explorer I can see that java is using that resource (This only happens when I try to delete the source, and bear in mind that trying to delete source directory is the last thing my program does)
And just to make me freak out even more, once I stop my java virtual machine, THEN the folder magically disappears. So Java did got the instruction right, it's just that is not willing to delete it until it's terminated
Running System.gc() before deleting the directory also didn't help, and my working directory is not the one I'm trying to delete
You can get this problem when using Files NIO calls which list or return a Stream of directory contents before deleting the directory.
Using try with resources on any Stream of Path returned by Files NIO can help prevent this issue:
try(Stream<Path> stream = Files.list(directory)) {
// do any work on contents - move / delete
}
// delete directory after closing stream above
I'm trying to write to a file in Java, or create a new file if the file doesn't exist. (Using JDK 14). However, when I run the following code I get an IOException at the if statement condition that reads The system could not find the file specified if the file doesn't exist, and Access is denied if the file does.
File file = new File(filePath);
System.out.println(filePath); // C:\Users\username\Documents\test.txt
if (file.createNewFile()) {
System.out.println("File successfully created");
} else {
System.out.println("File already exists");
}
The code works when I attempt to save it to the desktop folder and saves the file successfully, but for whatever reason isn't allowed to touch Documents.
The user I'm running IntelliJ as has full access to all files on the computer, and running the IDE as administrator did not fix the problem. However, I can save to the user folder and the desktop. It is only Documents or child directories of it that I can't save to.
There are a few similar questions on the site such as this one, however the cause is not the same as in my case this is a permissions issue, and not an issue of a missing directory.
I've just hit this same issue. It seems that JFileChooser() on some Windows 10 installations doesn't tell the os that the user has selected a folder and as such Sandboxing, Malware Control, Access control blocks access to create a file even though the user had full access (permission checks are OK but file write fails with IOException 13 or Access Denied). However FileDialog() DOES work where JFileChooser fails...
Heres what I would do to try to debug this:
Should you be trying to save to 'My Documents' as opposed to 'Documents'?
Try to save the file to C:\Users\username\test.txt (I suspect that will work)
Try to save the file to C:\Users\username\My Documents\test.txt
If you really do want to save it to 'Documents' make sure the 'Documents' director exists.
If thats the case, open the properties on Documents under the security tab select Everyone under 'Group our user names' and 'Full control' under permissions. that will open it wide up and should allow file creation. you might want to take note of what the settings where so you can put them back as setting a directory to wide open permissions can be 'problematic'. try running the program again.
1
if you want write data to file just user any Writer For example:
FileWriter writer = new FileWriter(yourFile);
You can use stream filtering for faster action.
Show more your code. You've just showed condition for existing file.
2
if you want create file in Documents folder, get a path, then make a:
File file = new File(documentPath);
while(!file.exists())
file.createNewFile();
//condition for file existing...`
If I don't help, comment below, just I can't understand your question :). Good Luck
I made a small Java program for academic purposes, its main focus is to read some .txt files and present the information to the user. These files are present in the resources folder, under the src folder.
The program runs as intended when launched from Eclipse.
Using the Launch4j app I was able to successfully create an exe which runs fine and does what's intended, up until I try to read the .txt files I have in the resources folder, which appears not to be able to reach.
I'm guessing that when I launch the exe the run time path would change to where the exe was created, so I created the program in a desktop folder and specified this path in the program, but that doesn't seem to solve the situation.
As an alternative, I moved the .txt files out of the program and once again created the exe in a desktop folder with said .txt files, linked the program to this path and once again it didn't work.
The command used to get the .txt files is:
Files.readAllLines(Paths.get(doc)).get(line)
And doc is simply the path to the intended .txt file.
It's worth noting that I have no previous experience in Java and throughout the development of the program I tried my best to use commands I'd fully understand and to keep it as simple as possible. I hope the solution can be along these lines! I'm very confident this must be a rookie mistake, but I can't seem to find the solution to this specific problem anywhere.
The paths to files in Eclipse are different than the paths to files in an .exe or JAR file.
I will let this other user explain it because I am lazy :p
Rather than trying to address the resource as a File just ask the
ClassLoader to return an InputStream for the resource instead via
getResourceAsStream:
InputStream in = getClass().getResourceAsStream("/file.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
As long as the file.txt resource is available on the classpath then
this approach will work the same way regardless of whether the
file.txt resource is in a classes/ directory or inside a jar.
The URI is not hierarchical occurs because the URI for a resource
within a jar file is going to look something like this:
file:/example.jar!/file.txt. You cannot read the entries within a jar
(a zip file) like it was a plain old File.
This is explained well by the answers to:
How do I read a resource file from a Java jar file?
Java Jar file: use resource errors: URI is not hierarchical
The original post is here, all credit to its author.
Fixing your URL should let you read from that file when you are using the .exe.
EDITED FOR CORRECTION. Thanks #VGR (see comments) for correcting my mistake.
I have a java code that creates a kml file and then the front-end code wants to read the file right away. The file creation is successful. But the problem is I need to refresh the project folder from Eclipse and then it can read the file. This is very obvious to read the file in such way.
My question is how to read the file from front-end code without refreshing the project folder. Is there any techniques?
Thanks in advance......
I'm not sure what the exact error is you get, but it might help if you create an empty file before the process and just append stuff during execution. That way the file is found without refresh.
I found the solution for this problem. Just create an empty file as the same name that you used inside your code and then put
Thread.sleep(2000);
after the file creation method.
Pretty simple :-)
My java code is unable to delete files on the the system hard drive.
Whenever file.delete() function is called, it returns false.
Any ideas, why that might be happening?
File.delete() can fail to delete a file for many reasons including:
you don't have correct permissions to delete the file
the file represents a directory and the directory is not empty
the file is locked by another process, (or even by the same process in say an unclosed FileOutputStream)
the file doesn't exist
File.delete() can return false if you are trying to delete a directory that is not empty, or the named file simply doesn't exist at the time of the call.
(if there is a permission issue, a SecurityException is thrown)
I had the same issue in my code and found that the culprit was actually an unclosed FileInputStream. After closing that FIS my file deleted without any problems. I hope this helps someone.
The usual reasons are insufficient permissions (although normally that would throw an exception), trying to delete a non-existant file or trying to delete a non-empty directory. Are you totally sure that you have permissions to delete the file you are trying to delete?
Some process might be reading/writing the file, so that it is locked. Or then your process does not have permissions to delete the file. If the file is a directory, all files inside it must be deleted first before the directory can be deleted. And finally there is the situation that the file does not exist, so the delete method will return false.
Windows? Use the Process Explorer to search for all processes which keep a handle (lock) on the file (or if this is a directory on any file inside of it).
On Linux, use fuser.
You might be trying to delete any file exists in C: Drive and on that you might not have the permissions to do so. Try to put it inside any other drive than C: and then run your code. Hope it works for you. :)
Make sure the file is not currently is use:
For example i was trying to delete a file using
f2.delete()
But it was unable to do as i was using BufferReader,FileWriter,BufferWriter etc.Close all those and then try.
buffer.close()
writer.close()
For those who are having trouble to delete file using file.delete(), your problem is that the file is still open.
Close buffer reader
Close File Writer
and most important CLOSE THE FILE before file.delete(), otherwise it will not delete.
Enjoy.