每当新文件被重命名时,它都应该放在一个文件夹中,这可能吗



下面是重命名现有Excel文件的代码,输出来自项目中的任何地方,但我希望在特定的文件夹中,输出应该使用Selenium web驱动程序/java随附当前日期和时间

package BrokenLink;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class newTestFile {
public static void main(String[] args)
{
CreateFileRenameExisting("PCPAutomation.xlsx");

当尝试添加文件夹详细信息时,会出现此异常-->C: \Users\skumari1\eclipse workspace\AlarmTest\genericFiles\PCPAutomation.xlsx(系统找不到指定的路径(-->无法提供文件夹地址

}
//Rename an existing file and create a new file
public static void CreateFileRenameExisting(String filename)
{
//get current project path
String filePath=System.getProperty("user.dir");
//create a new file
File file=new File(filePath+"\"+filename);
try {
if(!file.exists()) {
Workbook wb1 = new XSSFWorkbook();
FileOutputStream fileOut1 = new FileOutputStream(filename);
wb1.write(fileOut1);
fileOut1.close();
//file.createNewFile();
System.out.println("File is created");
}
else
{
File backupFile=new File(filePath+"\"+ Validatedate()  +  file.getName());
System.out.println("File already exist and backup file is created");
file.renameTo(backupFile);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static String Validatedate() {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH_mm_ss");
Date date = new Date();
String date1= dateFormat.format(date);
// System.out.println("Current date and time is " +date1);
return date1;
}
}

请帮我处理上面的代码,这样我就可以在上面的代码中给出文件夹地址,提前谢谢

我的第一个想法是文件夹还不存在。对一些人来说,这可能有点违背直觉,但Java不会创建文件夹来将新文件放入其中。在将文件放入文件夹之前,必须确保文件夹存在,例如:

void writeToFile(File file) throws IOException {
File folder = file.getParentFile();
if (!folder.exists()) {
folder.mkdirs();
}
//... create file and write into it
}

此外,File::mkdirs方法返回boolean,因此如果创建失败,则返回false。出于这个原因,我通常手动抛出IOException

if (!folder.mkdirs()) throw new IOException("Failed to create folder: " + folder.getAbsolutePath());

最新更新