In this API guide, we will learn important APIs/methods of java.nio.file.Files class with an example.
The Java NIO Files class (java.nio.file.Files) provides several methods for manipulating files in the file system. This Java NIO Files guide will cover the most commonly used of these methods. The Files class contains many methods, so check the JavaDoc too, if you need a method that is not described here.
The java.nio.file.Files class works with java.nio.file.Path instances, so you need to understand the Path class before you can work with the Files class.
The Java NIO Files class (java.nio.file.Files) provides several methods for manipulating files in the file system. This Java NIO Files guide will cover the most commonly used of these methods. The Files class contains many methods, so check the JavaDoc too, if you need a method that is not described here.
The java.nio.file.Files class works with java.nio.file.Path instances, so you need to understand the Path class before you can work with the Files class.
1. Files.createFile() API/Method
This method creates a new and empty file, failing if the file already exists. The check for the existence of the file and the creation of the new file if it does not exist are a single operation that is atomic with respect to all other filesystem activities that might affect the directory.
Java Files.createFile() Example
package net.javaguides.corejava.io;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class JavaCreateFile {
public static void main(String[] args) throws IOException {
Path myPath = Paths.get("src/myfile.txt");
if (Files.exists(myPath)) {
System.out.println("File already exists");
} else {
Files.createFile(myPath);
System.out.println("File created");
}
}
}
Output:
File created
2. Files.readAllLines() API/Method
This method read all lines from a file. This method ensures that the file is closed when all bytes have been read or an I/O error, or other runtime exception, is thrown. Bytes from the file are decoded into characters using the specified charset.
Java Files.readAllLines() API Example
In this example, we are reading all the lines of below JavaReadFile.java program itself.
package net.javaguides.corejava.io;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
public class JavaReadFile {
public static void main(String[] args) throws IOException {
Path myPath = Paths.get("src/net/javaguides/corejava/io/JavaReadFile.java");
List < String > lines = Files.readAllLines(myPath, StandardCharsets.UTF_8);
lines.forEach(line - > System.out.println(line));
}
}
Output:
package net.javaguides.corejava.io;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
public class JavaReadFile {
public static void main(String[] args) throws IOException {
Path myPath = Paths.get("src/net/javaguides/corejava/io/JavaReadFile.java");
List<String> lines = Files.readAllLines(myPath, StandardCharsets.UTF_8);
lines.forEach(line -> System.out.println(line));
}
}
3. Files.write() API/Method
This method is used to write lines of text to a file. Each line is a char sequence and is written to the file in sequence with each line terminated by the platform's line separator, as defined by the system property line.separator. Characters are encoded into bytes using the specified charset.
Java Files.write() API Example
In the example, we write four text lines to a file located at "src/resources/myfile.txt".
package net.javaguides.corejava.io;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.List;
public class JavaWriteFile {
public static void main(String[] args) throws IOException {
Path myPath = Paths.get("src/resources/myfile.txt");
List < String > animals = new ArrayList < > ();
// Adding new elements to the ArrayList
animals.add("Lion");
animals.add("Tiger");
animals.add("Cat");
animals.add("Dog");
System.out.println(animals);
Files.write(myPath, animals, StandardCharsets.UTF_8,
StandardOpenOption.CREATE);
System.out.println("Data written");
}
}
Output:
Data written
4. Files.deleteIfExists(Path path) API/Method
This method deletes a file if it exists.
Java Files.deleteIfExists() API Example
package net.javaguides.corejava.io;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class JavaDeleteFile {
public static void main(String[] args) throws IOException {
Path myPath = Paths.get("src/sample1.txt");
boolean fileDeleted = Files.deleteIfExists(myPath);
if (fileDeleted) {
System.out.println("File deleted");
} else {
System.out.println("File does not exist");
}
}
}
Output:
File deleted
5. Files.move() API/Method
This method used to move or rename a file to a target file.
By default, this method attempts to move the file to the target file, failing if the target file exists except if the source and target are the same file, in which case this method has no effect.
Java Files.move() API Example
package net.javaguides.corejava.io;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class JavaMoveFile {
public static void main(String[] args) throws IOException {
Path myPath = Paths.get("src/myfile.txt");
Path myPath2 = Paths.get("src/myfile2.txt");
Files.move(myPath, myPath2);
System.out.println("File moved");
}
}
Output:
File moved
6. Files.copy() API/Method
This method copy a file to a target file.
This method copies a file to the target file with the options parameter specifying how the copy is performed. By default, the copy fails if the target file already exists or is a symbolic link, except if the source and target are the same file, in which case the method completes without copying the file.
Java Files.copy() API Example
Let's first create a file named "sample1.txt" and enter some text in it. Once you run below program, the content of "sample1.txt" file should be copied to "sample2.txt" file:
package net.javaguides.corejava.io;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
public class JavaCopyFile {
public static void main(String[] args) throws IOException {
File source = new File("src/sample1.txt");
File dest = new File("src/sample2.txt");
Files.copy(source.toPath(), dest.toPath(),
StandardCopyOption.REPLACE_EXISTING);
}
}
7. Files.getOwner() API/Method
This method returns the owner of a file.
The path parameter is associated with a file system that supports FileOwnerAttributeView.
This file attribute view provides access to a file attribute that is the owner of the file.
Java Files.getOwner API Example
In the example, we get the owner of the file in Java.
package net.javaguides.corejava.io;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.UserPrincipal;
public class JavaGetFileOwner {
public static void main(String[] args) throws IOException {
Path myPath = Paths.get("src/sample.txt");
UserPrincipal userPrincipal = Files.getOwner(myPath);
String owner = userPrincipal.getName();
System.out.println(owner);
}
}
Output:
Ramesh\CM-1787
8. Append to file with Files.write() API
This example appends data with Files.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class JavaAppendFileFiles {
public static void main(String[] args) throws IOException {
String fileName = "src/main/resources/sample.txt";
byte[] tb = "Ramesh \n".getBytes();
Files.write(Paths.get(fileName), tb, StandardOpenOption.APPEND);
}
}
9. Java creates a directory with Files.createDirectory() API/Method
The example creates a new directory with Files.createDirectory().
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class JavaCreateDirectory {
public static void main(String[] args) throws IOException {
String fileName = "/home/ramesh/tmp/newdir";
Path path = Paths.get(fileName);
if (!Files.exists(path)) {
Files.createDirectory(path);
System.out.println("Directory created");
} else {
System.out.println("Directory already exists");
}
}
}
10. Java file size with Files.size() API/Method
The code example determines the file size using the Files' size() method.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class JavaFileSizeExample {
public static void main(String[] args) throws IOException {
String fileName = "src/main/resources/words.txt";
Path filePath = Paths.get(fileName);
long fileSize = Files.size(filePath);
System.out.format("The size of the file: %d bytes", fileSize);
}
}
Output:
The size of the file: 200 bytes
Comments
Post a Comment
Leave Comment