Скопируйте файл Excel в папку, созданную по адресу specfi c в java - PullRequest
2 голосов
/ 21 января 2020

У меня есть Excel в качестве входных данных для уверенных, и мне нужно скопировать тот же файл Excel в указанном месте, который генерируется на основе текущей даты и времени, например, папка, например, 202001201447 / конкретная c имя папки Я написал код для папки творения. Ниже приведен код

public static void writeRequestAndResponse() {  


        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");

        String currentDateTime = format.format(date);

        String folderPath = "E:\\OutQA\\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;
            } 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");
        }


       }

У меня проблема с копированием файла Excel. Я должен скопировать файл Excel в папку, созданную в указанных местах c. Ниже приведен код копии

public static void testcopy(String srcpath,String destpath)
    {

       FileInputStream instream = null;
        FileOutputStream outstream = null;

            try{
                File infile =new File(srcpath);
                File outfile =new File(destpath);

                instream = new FileInputStream(infile);
                outstream = new FileOutputStream(outfile);

                byte[] buffer = new byte[1024];

                int length;
                /*copying the contents from input stream to
                 * output stream using read and write methods
                 */
                while ((length = instream.read(buffer)) > 0){
                    outstream.write(buffer, 0, length);
                }

                //Closing the input/output file streams
                instream.close();
                outstream.close();

                System.out.println("File copied successfully!!");

            }catch(IOException ioe){
                ioe.printStackTrace();
             }


    }

1 Ответ

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

Посмотрите на новые java.nio.file -пакеты.

Там вы найдете java.nio.file.Files.copy, который принимает в качестве первого аргумента java.nio.file.Path к исходному файлу и в качестве второго аргумента указание Path к целевому местоположению.

A Path может быть создан следующим образом (я покажу его с вашим целевым местоположением, вам придется самостоятельно адаптироваться к вашему исходному местоположению):

Path targetLocation = Path.of("E:", "OutQA", "Output", currentDateTime);
File theDir = targetLocation.toFile();
Path targetFile = targetLocation.resolve(targetFilename);

Затем вызовите метод копирования следующим образом:

Files.copy(sourceFile, targetFile);

В качестве третьего параметра вы можете указать параметры, например, что делать, когда целевой файл уже существует (java.nio.file.StandardCopyOption). Этот параметр является необязательным.

...