I am trying to download a receipt file using selenium , every time i download the system is giving random number as name for the file downloading. Is it possible to change the file name while downloading? please see the number file name generated
is it possible to change the file name while saving . please help. thanks
CodePudding user response:
To do so you use the below hack: First set the default download folder path and then rename the file inside that folder to whatever you need to.
1) First you need to set the path of the download folder to a specific folder using chromeoption capabilities. Sample code:
WebDriverManager.chromedriver().setup();
ChromeOptions options = new ChromeOptions();
String downloadFilepath = System.getProperty("user.dir") "/downloads/";
System.out.println("Chrome Download path set to: " downloadFilepath);
File downloadtoFolder = new File(downloadFilepath);
if (!downloadtoFolder.exists()) {
downloadtoFolder.mkdir();
}
Map<String, Object> prefs = new HashMap<>();
prefs.put("credentials_enable_service", false);
prefs.put("profile.password_manager_enabled", false);
prefs.put("profile.default_content_settings.popups", 0);
prefs.put("download.prompt_for_download", false);
//This will set the path of the download folder
prefs.put("download.default_directory", downloadFilepath);
prefs.put("profile.default_content_setting_values.notifications", 1);
prefs.put("profile.default_content_settings.cookies", 1);
options.setExperimentalOption("prefs", prefs);
WebDriver driver = new ChromeDriver(options);
2) Below Method will rename file bases on two arguments a) new file name and b) directory path
Sample code:
private static void fileRename(String newFileName, String folder) {
File file = new File(folder);
System.out.println("Reading this " file.toString());
if (file.isDirectory()) {
File[] files = file.listFiles();
List<File> filelist = Arrays.asList(files);
filelist.forEach(f -> {
System.out.println(f.getAbsolutePath());
String newName = folder newFileName;
System.out.println(newName);
boolean isRenamed = f.renameTo(new File(newName));
if (isRenamed)
System.out.println(String.format("Renamed this file %s to %s", f.getName(), newName));
else
System.out.println(String.format("%s file is not renamed to %s", f.getName(), newName));
});
}