To read a file using Java 7's Files class, you can use the readAllLines or readAllBytes methods.
Here's an example of how to use these methods:
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.charset.StandardCharsets;
import java.io.IOException;
import java.util.List;
public class ReadFileExample {
public static void main(String[] args) {
String fileName = "path/to/your/file.txt";
try {
// Read all lines of the file into a list of strings
List<String> lines = Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8);
for (String line : lines) {
System.out.println(line);
}
// Read all bytes of the file into a byte array
byte[] bytes = Files.readAllBytes(Paths.get(fileName));
System.out.println(new String(bytes, StandardCharsets.UTF_8));
} catch (IOException ex) {
System.out.println("Error reading file: " + ex.getMessage());
}
}
}
In this example, we first create a String variable called fileName to store the path of the file we want to read. Then, we use the Paths.get method to create a Path object from the fileName string.
Next, we use the readAllLines method to read all the lines of the file into a list of strings. We pass the Path object to this method along with the StandardCharsets.UTF_8 parameter to specify the character encoding of the file. We then use a for loop to iterate over the lines of the file and print each line to the console.
After that, we use the readAllBytes method to read all the bytes of the file into a byte array. We pass the Path object to this method without specifying the character encoding, since this method reads the file as a sequence of bytes. We then create a String object from the byte array using the String constructor that takes a byte array and a character encoding as parameters, and print the string to the console.
Finally, if an IOException occurs while reading the file, we catch it and print an error message to the console.