How do I create and delete a file in JDK 7?

In this example you’ll learn how to create and delete a file. Using the new Files class helper from the JDK 7 you can create a file using the Files.createFile(Path) method. To delete a file you can use the Files.delete(Path) method.

Before create a file and delete a file we can check to see if the file is exist or not using the Files.exists(Path) method. In the code snippet below we’ll create a file when the file is not exist. And we’ll delete the file if the file is exist.


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

public class CreateDeleteFile {
    public static void main(String[] args) {
        try {
            // Create a config.cfg file under D:Temp directory.
            Path path = Paths.get("D:/Temp/config.cfg");
            if (!Files.exists(path)) {

            // Delete the path.cfg file specified by the Path.
            if (Files.exists(path)) {
        } catch (Exception e) {

How do I remove some characters from a StringBuffer?

The example below show you to remove some elements of the StringBuffer. We can use the delete(int start, int end) method call to remove some characters from the specified start index to end end index. We can also remove a character at the specified index using the deleteCharAt(int index) method call.

package org.kodejava.example.lang;

public class StringBufferDelete {
    public static void main(String[] args) {
        String text = "Learn Java by Examples";

        // Creates a new instance of StringBuffer and initialize
        // it with some text.
        StringBuffer sb = new StringBuffer(text);
        System.out.println("Original text  = " + sb.toString());

        // We'll remove a sub string from this StringBuffer starting
        // from the first character to the 10th character.
        sb.delete(0, 10);
        System.out.println("After deletion = " + sb.toString());

        // Removes a char at a specified index from the StringBuffer.
        // In the example below we remove the last character.
        sb.deleteCharAt(sb.length() - 1);
        System.out.println("Final result   = " + sb.toString());

Output of the program is:

Original text  = Learn Java by Examples
After deletion =  by Examples
Final result   =  by Example