I am having a tough time deleting a file. I will show you what is working, and you can be the judge if this is acceptable.
class StupidService{
def doThings(){
def tmpDirString = "dumpit"
def currentDir = new File("../${tempDirString}")
currentDir.eachFile(FileType.FILES){
def f=it
def answer = SuperComplicatedService.doStuff(f)
//this works, now I need to move the file to the "done" folder
File dir = new File("../${tempDirString}/done");
def endupFile = new File("../${tempDirString}/done/${f.name}")
FileUtils.copyFile(f, endupFile)
//this works; the file is copied to where I want it successfully; now I just need to delete the initial file.
def thisIsAJoke=0
while(f.delete()==false){
println "This is not a joke: ${thisIsAJoke}"
thisIsAJoke++
}
}
}
}
And so this prints out between 40k and 150k lines of "This is not a joke: 64457" etc. and then finally deletes the file.
What is going on?
What does SuperComplicatedService.doStuff(f) do? If it opens the file, make sure it closes it before returning. Otherwise, you won't be able to delete the file until the garbage collector collects the object that references it.
See I can't delete a file in java
Code for delete a file and folder of the file in Groovy/Grails
String filePath = "c:/dir"+"/"+"carpeta"+"/"+documentoInstance.nombreArchivo
String folderPath = "c:/dir"+"/"+"carpeta"+"/"
boolean fileSuccessfullyDeleted = new File(filePath).delete()
boolean folderSuccessDeleted = new File(folderPath).deleteDir()
if(fileSuccessfullyDeleted && folderSuccessDeleted){
documentoInstance.delete flush:true
}
else{
flash.error = "Archivo no borrado."
return
}
Related
Files inside the (Tracks)directory was not deleted. The method deletes the wav files stored in the directory.
public boolean deleteTrack(response) {
ListIterator<Track> trackListIterator = this.trackList.listIterator();
//tracklist is the linked list on which I'm using list iterator. I'm storing song which is a object inside it. this object has a fn() that returns content root path not absolute path.
String path = "";
while (trackListIterator.hasNext()) {
//RESPONSE == PARAMETER
if (trackListIterator.next().getTrackName().equals(response)) {
trackListIterator.previous();
path = trackListIterator.next().getTrackPath();//this is the fn() that
returns content root path example(src/Exploit/org/Trackstore/Music/Action Movie Music-FesliyanStudios.wav).
break;
}
}
File file = new File(path);
//here I'm taking absolute path for deleting actual wav file from the computer.
File toBeDeleted = new File(file.getAbsolutePath());
return toBeDeleted.delete();// returns false everytime.
}
The old API has many issues. For example, most methods return a boolean to indicate the result which is stupid and unjavalike - fortunately, there is a new API that fixes these issues.
Use it and you'll know WHY it failed. If that's too much effort, well, there isn't much to say. It didn't delete. No idea why, and there's no way to ask that API about why.
The new API lives in the java.nio.file package.
Replace this:
File f = new File("path/to/file");
if (!f.delete()) { ... it didn't work ... }
with:
Path p = Paths.get("path/to/file");
try {
Files.delete(p);
} catch (IOException e) {
// the exception will explain everything there is to be said about why it did not work!
}
I'm trying to wait for a file to get downloaded using fluent wait. But since the file downloads with different date format. I want to validate with "Partial filename" of the file using fluentWait. For Eg: cancelled_07092019, cancelled_09_07_2019. So here the filename 'canceled_' remains constant
Below code works fine for the actual filename.
Downloaded_report= new File("DownloadPath");
FluentWait<WebDriver> wait = new FluentWait<WebDriver>(driver);
wait.pollingEvery(1, TimeUnit.SECONDS);
wait.withTimeout(15, TimeUnit.SECONDS);
wait.until(x -> downloaded_report.exists());
Here, I want to check the startof the file name. How do I do this?
Thanks in Advance
I am not sure if I understood the question correctly but you can check if the file with the partial name exists in the given directory.
File dir = new File("DownloadPath");
String partialName = downloaded_report.split("_")[0].concat("_"); //get cancelled and add underscore
FluentWait<WebDriver> wait = new FluentWait<WebDriver>(driver);
wait.pollingEvery(1, TimeUnit.SECONDS);
wait.withTimeout(15, TimeUnit.SECONDS);
wait.until(x -> {
File[] filesInDir = dir.listFiles();
for (File fileInDir : filesInDir) {
if (fileInDir.getName().startsWith(partialName)) {
return true;
}
}
return false;
});
In the above code, we list all files in the download path directory. Then, iterate over each file, get its name and check if it contains the partial name that we want.
It might be a problem if you have multiple reports in the directory. Then I would advise clearing DownloadPath from files that start with cancelled_ in some kind of #Before hook.
This is currently what I have to delete the file but it's not working. I thought it may be permission problems or something but it wasn't. The file that I am testing with is empty and exists, so not sure why it doesn't delete it.
UserInput.prompt("Enter name of file to delete");
String name = UserInput.readString();
File file = new File("\\Files\\" + name + ".txt");
file.delete();
Any help would be GREATLY appreciated!
I now have:
File file = new File(catName + ".txt");
String path = file.getCanonicalPath();
File filePath = new File(path);
filePath.delete();
To try and find the correct path at run time so that if the program is transferred to a different computer it will still find the file.
The problem could also be due to any output streams that you have forgotten to close. In my case I was working with the file before the file being deleted. However at one place in the file operations, I had forgotten to close an output stream that I used to write to the file that was attempted to delete later.
Be sure to find out your current working directory, and write your filepath relative to it.
This code:
File here = new File(".");
System.out.println(here.getAbsolutePath());
... will print out that directory.
Also, unrelated to your question, try to use File.separator to remain OS-independent. Backslashes work only on Windows.
I got the same problem! then realized that my directory was not empty. I found the solution in another thread: not able to delete the directory through Java
/**
* Force deletion of directory
* #param path
* #return
*/
static public boolean deleteDirectory(File path) {
if (path.exists()) {
File[] files = path.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
deleteDirectory(files[i]);
} else {
files[i].delete();
}
}
}
return (path.delete());
}
Try closing all the FileOutputStream/FileInputStream you've opened earlier in other methods ,then try deleting ,worked like a charm.
I suspect that the problem is that the path is incorrect. Try this:
UserInput.prompt("Enter name of file to delete");
String name = UserInput.readString();
File file = new File("\\Files\\" + name + ".txt");
if (file.exists()) {
file.delete();
} else {
System.err.println(
"I cannot find '" + file + "' ('" + file.getAbsolutePath() + "')");
}
If you want to delete file first close all the connections and streams.
after that delete the file.
In my case it was the close() that was not executing due to unhandled exception.
void method() throws Exception {
FileInputStream fis = new FileInputStream(fileName);
parse(fis);
fis.close();
}
Assume exception is being thrown on the parse(), which is not handled in this method and therefore the file is not closed, down the road, the file is being deleted, and that delete statement fails, and do not delete.
So, instead I had the code like this, then it worked...
try {
parse(fis);
}
catch (Exception ex) {
fis.close();
throw ex;
}
so basic Java, which sometimes we overlook.
As other answers indicate, on Windows you cannot delete a file that is open. However one other thing that can stop a file from being deleted on Windows is if it is is mmap'd to a MappedByteBuffer (or DirectByteBuffer) -- if so, the file cannot be deleted until the byte buffer is garbage collected. There is some relatively safe code for forcibly closing (cleaning) a DirectByteBuffer before it is garbage collected here: https://github.com/classgraph/classgraph/blob/master/src/main/java/nonapi/io/github/classgraph/utils/FileUtils.java#L606 After cleaning the ByteBuffer, you can delete the file. However, make sure you never use the ByteBuffer again after cleaning it, or the JVM will crash.
How can I set a last modified date of a file using jimfs?
I have smth. like this:
final FileSystem fileSystem = Jimfs.newFileSystem(Configuration.unix());
Path rootPath = Files.createDirectories(fileSystem.getPath("root/path/to/directory"));
Path filePath = rootPath.resolve("test1.pdf");
Path anotherFilePath = rootPath.resolve("test2.pdf");
After creating the stuff I then create a directory iterator like:
try (final DirectoryStream<Path> dirStream = Files.newDirectoryStream(rootPath, "*.pdf")) {
final Iterator<Path> pathIterator = dirStream.iterator();
}
After that I iterate over the files and read the last modified file, which I then return:
Path resolveLastModified(Iterator<Path> dirStreamIterator){
long lastModified = Long.MIN_VALUE;
File lastModifiedFile = null;
while (dirStreamIterator.hasNext()) {
File file = new File(dirStreamIterator.next().toString());
final long actualLastModified = file.lastModified();
if (actualLastModified > lastModified) {
lastModifiedFile = file;
lastModified = actualLastModified;
}
}
return lastModifiedFile.toPath();
}
The problem is that both files "test1.pdf" and "test2.pdf" have lastModified being "0" so I actually can't really test the behavior as the method would always return the first file in the directory. I tried doing:
File file = new File(filePath.toString());
file.setLastModified(1);
but the method returns false.
UDPATE
I just saw that File#getLastModified() uses the default file system. This means that the default local file system will be used to read the time stamp. And this means I am not able to create a temp file using Jimfs, read the last modified and then assert the paths of those files. The one will have jimfs:// as uri scheme and the another will have OS dependent scheme.
Jimfs uses the Java 7 file API. It doesn't really mix with the old File API, as File objects are always tied to the default file system. So don't use File.
If you have a Path, you should use the java.nio.file.Files class for most operations on it. In this case, you just need to use
Files.setLastModifiedTime(path, FileTime.fromMillis(millis));
i am newbie in this but here is my point of view if you choose 1 specific FOLDER and you want to extract the last file from it.
public static void main(String args[]) {
//choose a FOLDER
File folderX = new File("/home/andy/Downloads");
//extract all de files from that FOLDER
File[] all_files_from_folderX = folderX.listFiles();
System.out.println("all_files_from_folderXDirectories = " +
Arrays.toString(all_files_from_folderX));
//we gonna need a new file
File a_simple_new_file = new File("");
// set to 0L (1JAN1970)
a_simple_new_file.setLastModified(0L);
//check 1 by 1 if is bigger or no
for (File temp : all_files_from_folderX) {
if (temp.lastModified() > a_simple_new_file.lastModified()) {
a_simple_new_file = temp;
}
//at the end the newest will be printed
System.out.println("a_simple_new_file = "+a_simple_new_file.getPath());
}
}}
Can anyone please tell me how to delete a file in a directory after being opened and loaded on to a database?
Here is my code:
public static void main(String[] args) throws SQLException{
int Count= 0;
File directory = new File("C://Documents and Settings//welcome//My Documents//Bluetooth Exchange Folder");
directory.deleteOnExit();
File files[] = directory.listFiles();
for(int index = 0; index < files.length; index++){
try {
FileReader inp = new FileReader (files[index]);
BufferedReader buf = new BufferedReader(inp);
String strLine;
try {
while ((strLine = buf.readLine()) != null)
{
System.out.println(strLine);
String[] dbColumnValues = strLine.split("%");
Connect.DoInsertIntoDB(Long.parseLong(dbColumnValues[0]),dbColumnValues[1],dbColumnValues[2], dbColumnValues[3]);
Count++;
System.out.println(Count + " Row(s) are inserted into the Database");
GenHTML.gen();
}
}
But the files are not deleted in the directory.
Please can anyone correct the mistake in my code?
[Currently, I am testing with 3 files in the directory. After each file gets loaded to the datbase, I want each files to get deleted from the directory.]
Thanks in advance!
It is better to be explicit in your code.
File files[] = directory.listFiles();
for(int index = 0; index < files.length; index++){
{
// Process files[index]
// ...
boolean wasDeleted = files[index].delete();
if (!wasDeleted)
{
// Deal with error
}
}
Also, you need to close your file handles when you are done with them
FileReader inp = new FileReader (files[index]);
try
{
// ...
}
finally
{
inp.close();
}
The File.delete() and File.deleteOnExit() methods will only delete a directory if it's empty. You'll have to delete the files from the directory as you process them (and make sure there are no subdirectories). Alternatively you can use FileUtils.deleteDirectory() from Apache Commons IO at the end of your processing.
The double slashes seems suspect. Either use a single backslash, which you need to quote as \\, or use a single slash /.
Also, you could try using delete() when then method returns instead of deleteOnExit().
According to the API:
Requests that the file or directory denoted by this abstract pathname be deleted when the virtual machine terminates.
In your code, however, you are treating that function as if it immediately deletes the directory.
You can't delete a directory, unless it's empty. If the directory is not empty, it is necessary to first recursively delete all files and subdirectories in the directory.
So directory.deleteOnExit() won't work in your case.
More, I suggest you to explicitly delete the files, not using deleteOnExit(). It is a dumb function that won't delete the file on exit if all the input/output streams related to the file are not closed. Always close the streams and explicitly delete the files, then the directory.
Maybe what you need to do is to use the dispose() method for the component that opens the file. What could possibly be the situation is that the file is still seen as opened and locked by a component that it had been opened in, so you have to ensure you use the dispose() method to solve that problem.