How to copy the contents of one folder to another?

1

Hello everyone. I have tried to copy the data from one folder to another using the input and output data implementing this method:

    public boolean creaArchivo1(String ruta, InputStream is)
        throws IOException {

        final int CHUNK_SIZE = 1024 * 4;
        OutputStream os = new BufferedOutputStream(new FileOutputStream(new File(ruta)));
        byte[] chunk = new byte[CHUNK_SIZE];
        int bytesLeidos = 0;

        while ( (bytesLeidos = is.read(chunk)) > 0) {

            os.write(chunk, 0, bytesLeidos);
        }
        os.close();
        String si="si";

        boolean verdadero=true;
        return verdadero;

    }

But do not copy the data if you know any other way or notice where it failed. Please tell me. Thanks.

    
asked by Abraham.P 01.02.2017 в 17:54
source

2 answers

2

If you are going to copy content you are probably referring to external storage, it is first important to assign permission:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

If you use Android 6.0+ you must request them in this way:

link

You can copy a directory to another route using this method:

public void copiarDirectorio(File sourceLocation , File targetLocation) {
    if (sourceLocation.isDirectory()) {
        if (!targetLocation.exists() && !targetLocation.mkdirs()) {
            Log.e("Error", "No puede crear directorio: " + targetLocation.getAbsolutePath());
        }
        String[] children = sourceLocation.list();
        for (int i=0; i<children.length; i++) {
            copyDirectory(new File(sourceLocation, children[i]),
                    new File(targetLocation, children[i]));
        }
    } else {
        File directory = targetLocation.getParentFile();
        if (directory != null && !directory.exists() && !directory.mkdirs()) {
            Log.e("Error", "No puede crear directorio: " + directory.getAbsolutePath());
        }

        try {
        InputStream in = new FileInputStream(sourceLocation);
        OutputStream out = new FileOutputStream(targetLocation);


        //Copa bits de inputStream to outputStream.
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();

        }catch(IOException ioe){
            Log.e("Error", "Error " + ioe.getMessage());
        }
    }
}
    
answered by 01.02.2017 / 20:53
source
1

Is not this simple solution useful? Through the two routes of the folders (the source and the destination) you can copy the data / files from one folder to another:

File origen = new File("C:\prueba\origen");
File destino = new File("C:\prueba\destino");
try {
    FileUtils.copyDirectory(origen, destino);
} catch (IOException e) {
    e.printStackTrace();
}
    
answered by 01.02.2017 в 18:00