--Use Files.readString and Path.of in Java 11 environment --Use Files.readAllLines, Files.readAllBytes and Paths.get in Java 7 environment
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
public class Cat {
public static void main(String[] args) throws IOException {
String path = args[0];
System.out.print(readString11(path));
System.out.print(readString7(path));
// String.join is Java 8 or later
System.out.println(String.join(System.lineSeparator(), readLines7(path)));
}
/**
*Read a text file. Methods available from Java 11.
* @param path path of the file to read
* @contents of return file
* @throws IOException
* @throws OutOfMemoryError
* @throws RuntimeException
*/
public static String readString11(String path) throws IOException {
return Files.readString(Path.of(path), Charset.forName("UTF-8"));
}
/**
*Read a text file. Methods available from Java 7.
* @param path path of the file to read
* @contents of return file
* @throws IOException
* @throws RuntimeException
*/
public static String readString7(String path) throws IOException {
return new String(Files.readAllBytes(Paths.get(path)), Charset.forName("UTF-8"));
}
/**
*Read a text file. Methods available from Java 7.
* @param path path of the file to read
* @contents of return file
* @throws IOException
* @throws RuntimeException
*/
public static List<String> readLines7(String path) throws IOException {
return Files.readAllLines(Paths.get(path), Charset.forName("UTF-8"));
}
}
compile.
$ javac Cat.java
Prepare a text file.
$ cat sample.txt
sample
sample
SANNPURU
Run the sample code.
$ java Cat sample.txt
sample
sample
SANNPURU
sample
sample
SANNPURU
sample
sample
SANNPURU
$ java -version
java version "11.0.1" 2018-10-16 LTS
Java(TM) SE Runtime Environment 18.9 (build 11.0.1+13-LTS)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.1+13-LTS, mixed mode)
$ uname -mrsv
Darwin 18.2.0 Darwin Kernel Version 18.2.0: Fri Oct 5 19:41:49 PDT 2018; root:xnu-4903.221.2~2/RELEASE_X86_64 x86_64
$ sw_vers
ProductName: Mac OS X
ProductVersion: 10.14.1
BuildVersion: 18B75
--English reference
--Japanese reference
Recommended Posts