How to move .zip folders created using Java.NIO FileSystem

258 Views Asked by At

I've created a .zip folder (compressed folder) using FileSystem, which is present in Java.nio package present in JDK 1.7 onwards.

        URI zipUri = new URI("jar:" + fileUri.getScheme(), fileUri.getPath(), null);
        FileSystem zipfs = FileSystems.newFileSystem(zipUri, env);

Now, I want to move the zipped folders from one directory to another, but I couldn't find any way to locate the zipped folders because it is a FileSystem and there is no method present to move it.

Files.move() works only with either file or directory, but not with zipped folders created from FileSystem.

Can anyone point me to the right direction pls?

1

There are 1 best solutions below

1
On

How to move file to another directory in Java

Java.io.File does not contains any ready make move file method, but you can workaround with the following two alternatives :

File.renameTo(). Copy to new file and delete the original file. In the below two examples, you move a file “C:\carpeta1\archivo.zip” from one directory to another directory with the same file name “C:\carpeta2\archivo2.zip“.

package com.softMolina.zip;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class MoveZipExample
{
    public static void main(String[] args)
    {

    InputStream inStream = null;
    OutputStream outStream = null;

        try{

            File carpetaA =new File("C:\\carpeta1\\archivo.txt");
            File carpetaB =new File("C:\\carpeta2\\archivo.txt");

            inStream = new FileInputStream(carpetaA);
            outStream = new FileOutputStream(carpetaB);

            byte[] buffer = new byte[1024];

            int length;
            //copy the file content in bytes
            while ((length = inStream.read(buffer)) > 0){

                outStream.write(buffer, 0, length);

            }

            inStream.close();
            outStream.close();

            //delete the original file
            afile.delete();

            System.out.println(".ZIP is copied successful!");

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