I tried to read and write files using StreamApi added in Java8. Please note that I am investigating and writing in about 30 minutes for verification (laugh)
SampleStream.java
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<br />
 *Character code is UTF-Set at 8(Shift_Cannot be referenced in jis)
 */
public class SampleStream {
	/**Read path*/
	private static final String INPUT_PATH = "C:\\temp\\in.txt";
	/**Output path*/
	private static final String OUTPUT_PATH = "C:\\temp\\out.txt";
	public static void main(String[] args) throws Exception {
		//Get FileSystem
		FileSystem fs = FileSystems.getDefault();
		//Set file path
		Path path = fs.getPath(INPUT_PATH);
		//Set the path for output
		Path out = fs.getPath(OUTPUT_PATH);
		//How to read part 1
		// Files.Read using 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");
		}
		//How to read part 2
		// Files.Read using readAllLines
		List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
		List<String> output = new ArrayList<String>();
		lines.stream().filter(s -> s.contains("link")).forEach(s -> output.add(s));
		//Pack the extracted data in a List and output it as text
		Files.write(out, output, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
		//Output the output data with the extended for statement and check
		for (String put : output) {
			System.out.println(put);
		}
	}
}
It seems that the character code only supports UTF-8, and an exception is thrown when trying to read with Shift_Jis.
I would like to publish the method of reading the directory hierarchy at a later date.
Recommended Posts