6.2. Use the Files class to check, delete, copy, or move a file or directory - Source Code

Code:

package c6.s2;

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

/**
 * @author Mikalai Zaikin
 */
public class FilesTest {

    public static void main(String... args) throws IOException {
        Path file = Paths.get("C:\\home\\zaikin\\foo\\test.txt");
        // Path target = Paths.get("C:\\home\\zaikin\\foo\\test1.txt");
        // Files.move(file, target, StandardCopyOption.REPLACE_EXISTING, LinkOption.NOFOLLOW_LINKS);

        Charset charset = Charset.forName("US-ASCII");
        try (BufferedReader reader = Files.newBufferedReader(file, charset)) {
            String line = null;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (NoSuchFileException x) {
            System.err.format("No such file: %s", x.getFile());
        } catch (IOException x) {
            System.err.println(x);
        }
    }
}
					

Code:

package c6.s2;

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

/**
 * @author Mikalai Zaikin
 */
public class TmpTest {

    public static void main(String... args) {
        try {
            Path tempFile1 = Files.createTempFile(null, ".myapp");
            Path tempFile2 = Files.createTempFile("mz", ".myapp");

            System.out.format("The temporary file: %s%n", tempFile1);
            System.out.format("The temporary file: %s%n", tempFile2);
        } catch (IOException x) {
            System.err.format("IOException: %s%n", x);
        }
    }
}
					

output:

The temporary file: C:\DOCUME~1\zaikin\LOCALS~1\Temp\6574291965064537777.myapp
The temporary file: C:\DOCUME~1\zaikin\LOCALS~1\Temp\mz949031777975367984.myapp
					

Professional hosting         Free 'Oracle Certified Expert Web Services Developer 6' Guide     Free SCDJWS 5.0 Guide