Скопировать файл Excel в папку, созданную на основе текущей даты в java - PullRequest
0 голосов
/ 22 января 2020

Проект должен скопировать файл 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 (Доступ запрещен ) "

Ответы [ 2 ]

0 голосов
/ 22 января 2020

Я не могу определить версию Java, которую вы используете. Следовательно, я использовал Java 8. Затем с этими 2 изменениями он работает.

  1. Files.copy() принимает Path экземпляров в Java 8 вместо 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" );
    }

}
0 голосов
/ 22 января 2020

Убедитесь, что файл Excel существует по тому же пути, и у файла есть права доступа. Попробуйте скопировать файл вручную и убедитесь, что

...