I am stuck up in a odd situation that is I am creating a file in a folder but I need to make sure that before the creation of a file if any file is there in the folder then it must be deleted only the current file which is process should be there.
since in my application every day a job runs which create the file in that folder so when ever presently job is running it should delete previous day file and no file should be there in afolder but the code that is shown below creates the file in that folder but the issue is that previous day file or if the job run multiple time on the same day also then those files are also thhere in the folder which should be deleted please advise how to achieve this..
File file = new File(FilePath + s); //path is c:\\abc folder & s is file name fgty.dat file
if (file.exists()) {
file.delete();
}
file.createNewFile();
Please advise
In your place I'd move the directory to a different name, say abc.OLD, recreate it and then create your file. If everything goes well, at the end you can remove the ols directory.
If different instances of your program could be running at the same time you need to implement some form of synchronization. A rather simplistic approach could be to check if the abc.OLD directory exists and abort execution if it does.
Without seeing more of your code, it sounds like you just need to empty the folder before opening a new file, since right now you're only deleting the file with the exact name that you're going to write. Use the list method of file objects.
File newFile = new File(FilePath + s);
for (File f : new File(FilePath).listFiles()) { // For each file in the directory, delete it.
f.delete();
}
newFile.createNewFile();
Note that this won't work if your folder contains other non-empty directories; you'll need a more robust solution. But the code above will at least delete all the files in the folder (barring Exceptions obviously) before creating the new file.
If, as you mentioned in the comments, you only want to delete *.dat files, it's as simple as putting a check in before you delete anything.
for (File f : new File(FilePath).listFiles()) { // For each file in the directory, delete it.
if (f.getName().endsWith(".dat")) { // Only delete .dat files
f.delete();
}
}
File file = new File(FilePath+"test.txt");
File folder = new File(FilePath);
File[] listOfFiles = folder.listFiles();
for(int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
System.out.println("File " + listOfFiles[i].getName());
listOfFiles[i].delete();
}
}
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
First I think you can have problems with the way you instanciate your Fileobject because if you don't have your path separator (\), you will try to create c:\abcfgty.dat instead of c:\abc\fgty.dat.
Use instead :
File file = new File(filePath, s);
Then you can delete the files ending by ".dat". As I understood, you don't need to delete sub directories. (Here is a link that tells you how. See also here)
for (File f : filePath.list()) { // For each file in the directory, delete it.
if(f.isFile() && file.getName().toLowerCase().endsWith(".dat");){
f.delete();
}
}
try {
file.createNewFile();
} catch (IOException ex) {
//Please do something here, at leat ex.printStackTrace()
}
Note that we can use a FileFilter to select the files to delete.
EDIT
As it was suggested in other answers, it might be preferable to move or rename the existing files instead of deleting them directly.
Related
I am trying to create lot of files in particular directory. If directory doesn't exist then it should create the directory and create bunch of files in it.
Whereever my program is running, it should create a "files" directory if it is not there and inside this "files" folder, I want to create bunch of files in it.
I have my below code but it looks like it is creating bunch of folders instead of one folder and all the files in that folder. What wrong I am doing?
for (Entry<String, String> entry : tasks.entrySet()) {
// looks like something is wrong here but can't figure out what wrong I am doing?
File file = new File("files/" + entry.getKey());
file.mkdirs();
try (BufferedWriter writer =
new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file),
StandardCharsets.UTF_8))) {
writer.write(entry.getValue());
} catch (IOException ex) {
// log error
}
}
For example, you're trying to create file C:\Stuff\Things\other.txt
With your current code, you create the folder C:\Stuff\Things\other.txt\
When you attempt to write to the file, moo.txt, it cannot, because you put a folder there (...\other.txt\)
Instead, create the folders up to, but not including the file name, before writing your file (C:\Stuff\Things\)
File file = new File(...);
file.getParentFile().mkdirs();
try(BufferedWriter ...
The problem I am having is that when I attempt to create the folder, it doesn't create. It might have something to do with the directory, but honestly I don't know. I tried using this:
File f = new File(javax.swing.filechooser.FileSystemView.getFileSystemView().getHomeDirectory() + "/Levels/First Folder/Levels");
try{
if(f.mkdir()) {
System.out.println("Directory Created");
} else {
System.out.println("Directory is not created");
}
} catch(Exception e){
e.printStackTrace();
}
But it didn't work for me.
And this is the directory I put in the File, but I want the program to work on any computer: C:\Users\(My name)\Desktop\Levels\First Folder\Levels
You said only the Desktop directory exists, so you'll need to use mkdirs to construct the whole directory tree:
File f = new File(javax.swing.filechooser.FileSystemView.getFileSystemView().getHomeDirectory() + "/Levels/First Folder/Levels");
try{
if(f.mkdirs()) { //< plural
System.out.println("Directory Created");
Keep in mind: you may want to check whether this directory exists before you try to create it, as it presumably isn't an error and is permissible to continue if your program has created it once before.
Recommending Files.createDirectories() instead of File.mkdirs() because handling errors is more straightforward.
Thus:
Files.createDirectories(Paths.get(System.getProperty("user.home"), "/Levels/First Folder/Levels"));
With mkdirs() it is difficult to determine if it failed, why it failed, or if it did not create the directory because it already existed.
I am writing a test to check that a file can be downloaded from a particular web page and I want it to be able to run both locally and remotely (i.e. on a node via Selenium grid). Before anyone links me to the 'do you really need to download the file?' article, I have already managed to download and check the file, I just need a way of deleting it after the test has completed. Just calling File.delete(); or similar will only work locally (as far as I'm aware) so I can't use that to delete the file from the node machine. I'm aware of the class org.openqa.selenium.io.TemporaryFileSystem however I can't find any instructions for how to use it.
Can anyone offer a better solution than 'just run a script on the node machine to delete the file'? Thanks!
You can make the download folder shared. \youruser\downloads after that you can pass this path to the File.Delete(); and it will delete the desired files.
Cleanup of downloaded files within session of Grid Node feature is planned:
https://github.com/SeleniumHQ/selenium/issues/11457
https://github.com/SeleniumHQ/selenium/issues/11657
This Worked for me
try
{
if ((new File("Path")).delete()) {
System.out.println("Pass");
} else {
System.out.println("Failed");
}
} catch (Exception ex) {
ex.printStackTrace();
}
----------simply use this code for delete file in any folder-------------------
File file = new File("C:\\Users\\Updoer\\Downloads\\Inspections.pdf");
if(file.delete())
System.out.println("file deleted");
The Below Code will sequentially delete all the files from folder
File path = new File("Path of Folder");
File[] files = path.listFiles();
for (File file : files) {
System.out.println("Deleted filename :"+ file.getName());
file.delete();
}
I am trying to remove a file in java, but it will not remove. Could someone explain why it won't remove?
Here is the code that I am using:
File bellFile = new File("config\\normbells.txt");
bellFile.delete();
File bellFileNew = new File("config\\normbells.txt");
bellFileNew.createNewFile();
System.out.println("Done!");
NOTE: I am trying to wipe the file, if that helps.
File deletion can fail under the following circumstances:
The file does not exist.
The file is a directory not a file.
You don't have access to delete the file.
You don't have access to the the file or any of its parent directory.
The file is being used currently by some another application.
Try avoiding all the above mentioned circumstances & you'll surely able to delete the file.
Also before deleting the file add this condition :
if (file.exists()) {
file.delete();
}
Java7 has new functionality for this.
Path target = Paths.get("D:\\Backup\\MyStuff.txt");
Files.delete(target);
Path newtarget = Paths.get("D:\\Backup\\MyStuff.txt");
Set<PosixFilePermission> perms
= PosixFilePermissions.fromString("rw-rw-rw-");
FileAttribute<Set<PosixFilePermission>> attr
= PosixFilePermissions.asFileAttribute(perms);
Files.createFile(newtarget, attr);
Take a look at the File class http://docs.oracle.com/javase/7/docs/api/java/io/File.html
File bellFile = new File("config\\normbells.txt");
if(bellFile.delete())
{
System.out.println("Done!");
}
I have a String like this "D:/Data/files/store/file.txt" now I want to check ,is directory is already exist or not, if not I want to create directory along with text file. I have tried mkdirs() but its creating directory like this data->files->store->file.txt. means its creates file.txt as folder, not a file. can any one kindly help me to do this. thanks in advance.
You need to run mkdirs() on parent directory, not the file itself
File file = new File("D:/Data/files/store/file.txt");
file.getParentFile().mkdirs();
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
Here you go...
boolean b = (new File("D:/Data/files/store/file.txt").getParentFile()).mkdirs();