-1

I am working on an application which will download 3rd party dependencies to a particular folder and then execute dependency check on it. The files downloaded can be of any type, they can be zip, jar or may b a folder. I am trying to find a code example but nothing seems to work for me. I tried NIO in java but that seems to work only for writing to a particular file not folder. Below is code where I used NIO


        // Checking If The File Exists At The Specified Location Or Not
        Path filePathObj = Paths.get(filePath);
        boolean fileExists = Files.exists(filePathObj);
        if(fileExists) {
            try {
                urlObj = new URL(sampleUrl);
                rbcObj = Channels.newChannel(urlObj.openStream());
                fOutStream = new FileOutputStream(filePath);

                fOutStream.getChannel().transferFrom(rbcObj, 0, Long.MAX_VALUE);
                System.out.println("! File Successfully Downloaded From The Url !");
            } catch (IOException ioExObj) {
                System.out.println("Problem Occured While Downloading The File= " + ioExObj.getMessage());
            } finally {
                try {
                    if(fOutStream != null){
                        fOutStream.close();
                    }
                    if(rbcObj != null) {
                        rbcObj.close();
                    }
                } catch (IOException ioExObj) {
                    System.out.println("Problem Occured While Closing The Object= " + ioExObj.getMessage());
                }
            }
        } else {
            System.out.println("File Not Present! Please Check!");
        }```
Rohail Usman
  • 119
  • 3
  • 12
  • 1
    Please read "How to create a [mcve]". Then use the [edit] link to improve your question (do not add more information via comments). Otherwise we are not able to answer your question and help you. Seriously: all Java APIs that allow you to write files "somewhere" include a way to define "somewhere". Thus it is really not clear what you are asking for. You are always putting files into some folder. – GhostCat Sep 25 '19 at 09:23
  • What do you mean by "but nothing seems to work for me"? What code did you try, what results did you expect and what did you get instead? – Pshemo Sep 25 '19 at 09:25
  • @GhostCat I want to download files with any kind of extension to a particular folder. – Rohail Usman Sep 25 '19 at 09:31
  • From your code the things that are kind of clear are "you pass the url of the file you want to download" which means .. you can download whatever you like as long as you have the url. Second you have a `FileOutputStream`, the `filePath` parameter is where the file will be written. meaning you already have defined the folder ( which is the full path minus the file name ). Other than that it is not clear what is your problem neither what you tried or how you approached the problem – Michael Michailidis Sep 25 '19 at 09:44
  • If you're using Java 11+ and the remote uses HTTP, check out the [`java.net.http`](https://docs.oracle.com/en/java/javase/13/docs/api/java.net.http/module-summary.html) module and particularly [`BodyHandlers#ofDownloadFile(Path,OpenOption...)`](https://docs.oracle.com/en/java/javase/13/docs/api/java.net.http/java/net/http/HttpResponse.BodyHandlers.html#ofDownloadFile(java.nio.file.Path,java.nio.file.OpenOption...)). – Slaw Sep 25 '19 at 09:46
  • You described what you want and there are many ways to achieve it and each one should work in normal circumstances. If some code like https://stackoverflow.com/a/24041297 doesn't do what you want then you should get at least some exception which would attempt to describe cause of the problem and you should include that description/stacktrace in the question. – Pshemo Sep 25 '19 at 09:52

2 Answers2

0
public Class CopyAndWrite {

    public static final String SOURCES = "C:\\Users\\Administrator\\Desktop\\resources";
    public static final String TARGET = "C:\\Users\\Administrator\\Desktop\\111";

    public static void main (String[]args) throws IOException {

        Path startingDir = Paths.get(SOURCES);

        Files.walkFileTree(startingDir, new FindJavaVisitor());
    }

    private static class FindJavaVisitor extends SimpleFileVisitor<Path> {

        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
            if (!StringUtils.equals(dir.toString(), SOURCES)) {
                Path targetPath = Paths.get(TARGET + dir.toString().substring(SOURCES.length()));
                if (!Files.exists(targetPath)) {
                    Files.createDirectory(targetPath);
                }
            }
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            Path targetPath = Paths.get(TARGET + file.toString().substring(SOURCES.length()));
            copyFile(targetPath, Files.readAllBytes(file));

            return FileVisitResult.CONTINUE;
        }
    }

    private static void copyFile (Path path,byte[] bytes){
        // write file
        try {
            Files.write(path, bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Deters
  • 1
  • 2
0

Using OKHttpClient to download the file and place in a folder.

        Request request = new Request.Builder().url(downloadUrl).build();
        Response response;
        try {
            response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                fileName = abc.zip
                Path targetPath = new File(inDir + File.separator + fileName).toPath();
                try (FileOutputStream fos = new FileOutputStream(targetPath)) {
                    fos.write(response.body().bytes());
                }
                return 0;
            }
        } catch (IOException e) {
            logger.error(e.getMessage());
        }```
Rohail Usman
  • 119
  • 3
  • 12