Java 8 Stream API Sample
- #Java
- #Tips
- #Know-how
- 2018/03/30
Sample code
I tried reading and writing files with the Stream API that shipped with Java 8.
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
/**
* Stream sample
* The character set is fixed to UTF-8 (Shift_JIS cannot be used).
*/
public class SampleStream {
/** Read path */
private static final String INPUT_PATH = "C:\\temp\\in.txt";
/** Write path */
private static final String OUTPUT_PATH = "C:\\temp\\out.txt";
public static void main(String[] args) throws Exception {
// Obtain the FileSystem
FileSystem fs = FileSystems.getDefault();
// Path to the source file
Path path = fs.getPath(INPUT_PATH);
// Path to the output file
Path out = fs.getPath(OUTPUT_PATH);
// Read pattern #1: use Files.lines
try (Stream<String> stream = Files.lines(path, StandardCharsets.UTF_8)) {
stream.filter(s -> s.contains("link"))
.map(s -> s.replace("html", "form"))
.map(s -> s.replace("action", "href"))
.forEach(System.out::println);
} catch (IOException e) {
System.out.println("error");
}
// Read pattern #2: use Files.readAllLines
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
List<String> output = new ArrayList<String>();
lines.stream().filter(s -> s.contains("link")).forEach(output::add);
// Write the extracted data to a text file
Files.write(out, output, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
// Print the output to verify it
for (String put : output) {
System.out.println(put);
}
}
}
- Apparently UTF-8 is the only supported encoding; trying Shift_JIS throws an exception.
Share:
X (Twitter)