import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
public class FileTest {
public static void main(String[] args) throws IOException {
Path filePath = Paths.get("data.txt");
// write a file line by line
List<String> lines = Arrays.asList("line 1", "line 2", "line 3");
Files.write(filePath, lines);
// check if file exists
if(!Files.exists(filePath)) {
System.out.println("file doesn't exist :-(");
return;
};
// read a file line by line
List lines = Files.readAllLines(filePath);
for (String line : lines) {
// Process the String line here!!
System.out.println(line);
};
// OR: read a file line by line with a Lambda (Java 8)
Files.lines(filePath).forEach(line -> {
// Process the String line here!!
System.out.println(line);
});
}
}
In Files.write() you can use also add Options, e.g. StandardOpenOption.CREATE or StandardOpenOption.APPEND. If omitted like above you get StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING.
More options to read/write also larger files in a buffered way are found here https://www.baeldung.com/java-read-file
superb information, thankyou for putting
ReplyDeletehmm
ReplyDeletezx
ReplyDelete