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();
}
Related
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 want to move files (images) from a folder to another:
For example:
/home/folder1/image.png
to
/home/folder1/folder2/image.png
And obviously remove the image from the folder1
I've trying to do it by reading the path and then modifying it, or using renameTo, but i can't do it.
I hope someone can help me a little with this, Thanks.
EDIT:
Well I can put the code but it's simple to explain what i did:
I just created a Folder class that has a File object of my folder (/home/folder1) , i read all the images inside and save it in an File array, then i scan it and try to change the path of every image file String to another
EDIT:
Thanks to all for the help, all are good examples, I was able to change my files to another location, there was a bunch of files I wanted to move so, I didn't want to create too many objects.
You said you tried renameTo and it didn't work, but this worked for me. After I renamed it I deleted the original file.
File a = new File("C:\\folderA\\A.txt");
a.renameTo(new File("C:\\folderB\\" + a.getName()));
a.delete();
In java 8+ you can simply use Files.move from nio:
try {
Path source = Paths.get("/home/folder1/image.png");
Path dest = Paths.get("/home/folder1/folder2/image.png");
Files.move(source, dest);
} catch (IOException e) {
...
}
The paths can even come from different file system providers (ie a ZipFileSystem).
Commons-io has a few methods in the FileUtils class that can help you.
http://commons.apache.org/proper/commons-io/javadocs/api-release/index.html?org/apache/commons/io/package-summary.html
Example:
FileUtils.moveFile(src, dest);
The usual approach to solving this is copying the file and then deleting it from the original location, but you can follow this tutorial for more information. Also, the platform(linux, windows, is not important).
I didn't run this, but it should work
File f1 = new File("/home/folder1/image.png");
File f2 = new File("/home/folder1/folder2/image.png");
f1.renameTo(f2);
There are many approaches for you to do that.
This snippet is one of them, you can move your files like this way:
try {
final File myFile = new File("C:\\folder1\\myfile.txt");
if(myFile.renameTo(new File("C:\\folder2\\" + myFile.getName()))) {
System.out.println("File is moved successful!");
} else {
System.out.println("File is failed to move!");
}
}catch(Exception e){
e.printStackTrace();
}
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.
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();
I have made a Swing application and will include a file, help.pdf in the .jar file. When the user selects Help->User Guide from a JMenuItem, it should load the file in the default PDF viewer on the system.
I have the code to load the PDF,
private void openHelp() {
try {
java.net.URL helpFile = getClass().getClassLoader().getResource("help.pdf");
File pdfFile = new File(helpFile.getPath());
if (pdfFile.exists()) {
if (Desktop.isDesktopSupported()) {
Desktop.getDesktop().open(pdfFile);
} else {
System.out.println("Awt Desktop is not supported!");
}
} else {
System.out.println("File does not exist!");
}
System.out.println("Done");
} catch (Exception ex) {
ex.printStackTrace();
}
}
This works in the eclipse IDE, however, when I pack it into a jar for other people it no longer works.
How do I fix this problem?
The problem is that a File cannot name a component of a JAR file. What you need to do is to copy the resource from the JAR file into a temporary file in the filesystem, and open using the File for the temporary file.
File names in a .jar file are case sensitive. In your text you write Help.pdf but in the code you use help.pdf. The upper/lowercase in the Java code must match the case of the file, even if you are using a system where the filesystem is not case sensitive.
Try
getResource("Help.pdf");
instead (assuming the filename in your posting text is correct)
I think you have to retrieve the location of the jar, open it and load the pdf file from within your application. The .jar file is just a zipped archive, which can be read with java easily...