将 Excel 文件复制到基于 java 中当前日期创建的文件夹



项目需要将excel文件从源复制到基于当前日期创建的目标文件夹。我可以创建当前的日期和时间文件夹,但无法将文件复制到那里。收到错误消息为"访问被拒绝">

public static void writeRequestAndResponse() throws IOException {   

Date date = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
String currentDateTime = format.format(date);
String folderPath = "E:\QA\Output\" + currentDateTime ;
File theDir = new File(folderPath);
// if the directory does not exist, create it
if (!theDir.exists()) {
System.out.println("creating directory: " + theDir.getName());
boolean result = false;          

try {
theDir.mkdirs();
result = true;
final String folderpath1 = folderPath + "\test.api\" + "\exceloutput";
File theDir1 = new File(folderpath1);
theDir1.mkdirs();
System.out.println(folderpath1);
String frompath = "E:\Project\src\main\java\com\qa\testdata\APITestData.xlsx";
//FileInputStream is = new FileInputStream(frompath);
File file1 = new File(frompath);
//String str1="E:\QA\Output\20200121172737\tc.api\exceloutput";
// File file2 = new File(str1);
final String topath=folderpath1;
File file2 = new File(topath);
//PrintWriter out = new PrintWriter(new FileOutputStream(topath));
//FileOutputStream outfs=  new FileOutputStream(topath);
Files.copy(file1,file2);

}
catch (SecurityException se) {
// handle it
System.out.println(se.getMessage());
}
if (result) {
System.out.println("Folder created");
}
} else if (theDir.exists()) {
System.out.println("Folder exist");
}

}

错误消息在控制台中显示为"java.io.FileNotFoundException: E:\QA\Output\20200122094149\test.api\exceloutput (Access is denied(">

我无法弄清楚您正在使用的Java版本。因此,我使用了Java 8。然后通过这两个更改,它正在工作。

  1. Files.copy()在 Java 8 中采用Path个实例,而不是File个实例。所以,改变了它。
  2. Files.copy()中,目标Path应指向文件而不是文件夹。

更改的代码(删除了注释代码(:

public static void writeRequestAndResponse(){
Date date = new Date();
SimpleDateFormat format = new SimpleDateFormat( "yyyyMMddHHmmss" );
String currentDateTime = format.format( date );
String folderPath = "E:\QA\Output\" + currentDateTime;
File theDir = new File( folderPath );
// if the directory does not exist, create it
if (!theDir.exists()) {
System.out.println( "creating directory: " + theDir.getName() );
boolean result = false;
try {
theDir.mkdirs();
result = true;
final String folderpath1 = folderPath + "\test.api\" + "\exceloutput";
File theDir1 = new File( folderpath1 );
theDir1.mkdirs();
System.out.println( folderpath1 );
String frompath = "E:\Project\src\main\java\com\qa\testdata\APITestData.xlsx";
File file1 = new File( frompath );
final String topath = folderpath1 + "\outputFile.xlsx"; //The output file name included
File file2 = new File( topath );
Files.copy( file1.toPath(), file2.toPath() );
} catch (Exception se) {
// handle it
System.out.println( se.getMessage() );
}
if (result) {
System.out.println( "Folder created" );
}
} else if (theDir.exists()) {
System.out.println( "Folder exist" );
}
}

请确保 excel 文件存在于同一路径上,并且该文件具有访问权限。尝试手动复制文件并检查

相关内容

  • 没有找到相关文章

最新更新