How do I move a file in JDK 7?

In the following code snippet you will learn how to move a file using the java.nio.file.Files helper class of JDK 7. This class simplify how you can move file. To move file you need to define the Path of the source and the target file.

We use the Files.move() method to move the file by passing the source and target path. We can also define the CopyOptions of the move process. For example to tell the move operation to replace the target file if the file already exist we can use the StandardCopyOption.REPLACE_EXISTING option. This option is a varargs, that means we can pass multiple options.

package org.kodejava.io;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import static java.nio.file.StandardCopyOption.*;

public class FileMoveDemo {
    public static void main(String[] args) {
        // Define the source and target of the file to be moved.
        Path source = Paths.get("F:/Temp/data.txt");
        Path target = Paths.get("F:/Temp/data.bak");

        try {
            // Move file from source to target using the defined
            // configuration (REPLACE_EXISTING)
            Files.move(source, target, REPLACE_EXISTING);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

How do I copy a file in JDK 7?

In this example you’ll see how to copy a file using the new API provided in the JDK 7. The first step is to define the source and the target of the file to be copied. For this we can use the Path class. To create an instance of Path we use the Paths.get() method by passing the path information as the arguments.

Next we can configure the file copy operation option. For this we can define it as an array of CopyOtion. We can use copy option such as StandardCopyOption.REPLACE_EXISTING and StandardCopyOption.COPY_ATTRIBUTES.

Finally, to copy the file we use the Files.copy() method. We give three arguments to this method, they are the source file, the target file and the copy options information.

Let’s see the code snippet below:

package org.kodejava.io;

import java.io.IOException;
import java.nio.file.*;

public class NioFileCopyDemo {
    public static void main(String[] args) {
        // Define the source and target of the file to be copied.
        Path source = Paths.get("D:/resources/data.txt");
        Path target = Paths.get("D:/resources/data.bak");

        // Define the options used in the file copy process.
        CopyOption[] options = new CopyOption[]{
                StandardCopyOption.REPLACE_EXISTING,
                StandardCopyOption.COPY_ATTRIBUTES
        };

        try {
            // Copy file from source to target using the defined 
            // configuration.
            Files.copy(source, target, options);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

How do I write a text file in JDK 7?

In JDK 7 we can write all lines from a List of String into a file using the Files.write() method. We need to provide the Path of the file we want to write to, the List of strings and the charsets. Each line is a char sequence and is written to the file in sequence with each line terminated by the platform’s line separator.

Let’s see the code snippet below:

package org.kodejava.io;

import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class WriteTextFile {
    public static void main(String[] args) {
        Path file = Paths.get("D:/resources/data.txt");

        List<String> lines = new ArrayList<>();
        lines.add("Lorem Ipsum is simply dummy text of the printing ");
        lines.add("and typesetting industry. Lorem Ipsum has been the ");
        lines.add("industry's standard dummy text ever since the 1500s, ");
        lines.add("when an unknown printer took a galley of type and ");
        lines.add("scrambled it to make a type specimen book.");

        try {
            // Write lines of text to a file.
            Files.write(file, lines, StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

This code snippet will create a file called data.txt under the resources folder. Please make sure that this folder is existed before you tried to run the code.

How do I use try-with-resources statement?

The try-with-resources statement is introduced in the Java 7. With this new statement we can simplify resource management in our program, also known as ARM (Automatic Resource Management).

This statement is a try statement that declares one or more resources. After the program finish with the resource, it must be closed. The try-with-resources ensures that each resource is closed and the end of the statement.

Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

package org.kodejava.basic;

import java.io.*;
import java.nio.charset.StandardCharsets;

public class TryWithResourceExample {
    public static void main(String[] args) {
        try {
            TryWithResourceExample demo = new TryWithResourceExample();
            demo.printStream("F:/tmp/data.txt");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void printStream(String fileName) throws IOException {
        char[] buffer = new char[1024];

        try (InputStream is = new FileInputStream(fileName);
             Reader reader = new BufferedReader(
                     new InputStreamReader(is, StandardCharsets.UTF_8))) {

            while (reader.read(buffer) != -1) {
                System.out.println(buffer);
            }
        }
    }
}

How do I use string in switch statement?

Starting from Java 7 release you can now use a String in the switch statement. On the previous version we can only use constants type of byte, char, short, int (and their corresponding reference / wrapper type) or enum constants in the switch statement.

The code below give you a simple example on how the Java 7 extended to allow the use of String in switch statement.

package org.kodejava.basic;

public class StringInSwitchExample {
    public static void main(String[] args) {
        String day = "Sunday";
        switch (day) {
            case "Sunday":
                System.out.println("doSomething");
                break;
            case "Monday":
                System.out.println("doSomethingElse");
                break;
            case "Tuesday":
            case "Wednesday":
                System.out.println("doSomeOtherThings");
                break;
            default:
                System.out.println("doDefault");
                break;
        }
    }
}