copy files from one directory to another code example

Example 1: copy all files from a folder to another ubuntu

cp -a ./source/. ./dest/

Example 2: linux copy

# Linux - Bash

# syntax:
# cp [option(s)] <source-filepath> <destination-filepath>

# example-1 (fundamental - no options):
cp "C:\Windows\System32\drivers\etc\hosts.txt" "C:\Users\hosts.txt"

# example-2 (fundamental - with options):
cp -nR "C:\Windows\System32\drivers\etc" "C:\Users"

# + ------ + ------------------------------------------------------- +
# | OPTION |  DESCRIPTION                                            |
# + ------ + ------------------------------------------------------- +
# |   -a   | archive files                                           |
# |   -f   | force copy by removing the destination file if needed   |
# |   -i   | interactive - ask before overwrite                      |
# |   -l   | link files instead of copy                              |
# |   -L   | follow symbolic links                                   |
# |   -n   | no file overwrite                                       |
# |   -R   | recursive copy (including hidden files)                 |
# + ------ + ------------------------------------------------------- +

Example 3: java copy file from one directory to another efficiently

private static void copyFileUsingStream(File source, File dest) throws IOException {
    InputStream is = null;
    OutputStream os = null;
    try {
        is = new FileInputStream(source);
        os = new FileOutputStream(dest);
        byte[] buffer = new byte[1024];
        int length;
        while ((length = is.read(buffer)) > 0) {
            os.write(buffer, 0, length);
        }
    } finally {
        is.close();
        os.close();
    }
}

Example 4: copy file in linux command line

cp [OPTION] Source Destination
cp [OPTION] Source Directory
cp [OPTION] Source-1 Source-2 Source-3 Source-n Directory

Example 5: how to copy file to another directory in linux

cp -r <FILEPATH> <WHEREYOUWANTTOCOPYTO>
#for example
cp -r /home/thor/asia.txt /home/thor/

Example 6: copy directory with files

cp -r source_folder destination/path

Tags:

Java Example