--Utilisez Files.readString et Path.of dans l'environnement Java 11 --Utilisez Files.readAllLines, Files.readAllBytes et Paths.get dans l'environnement Java 7
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.la jointure est Java 8 ou version ultérieure
        System.out.println(String.join(System.lineSeparator(), readLines7(path)));
    }
    /**
     *Lisez le fichier texte. Méthodes disponibles à partir de Java 11.
     * @param path Le chemin du fichier à lire
     * @contenu du dossier de retour
     * @throws IOException
     * @throws OutOfMemoryError
     * @throws RuntimeException
     */
    public static String readString11(String path) throws IOException {
        return Files.readString(Path.of(path), Charset.forName("UTF-8"));
    }
    /**
     *Lisez le fichier texte. Méthodes disponibles à partir de Java 7.
     * @param path Le chemin du fichier à lire
     * @contenu du dossier de retour
     * @throws IOException
     * @throws RuntimeException
     */
    public static String readString7(String path) throws IOException {
        return new String(Files.readAllBytes(Paths.get(path)), Charset.forName("UTF-8"));
    }
    /**
     *Lisez le fichier texte. Méthodes disponibles à partir de Java 7.
     * @param path Le chemin du fichier à lire
     * @contenu du dossier de retour
     * @throws IOException
     * @throws RuntimeException
     */
    public static List<String> readLines7(String path) throws IOException {
        return Files.readAllLines(Paths.get(path), Charset.forName("UTF-8"));
    }
}
compiler.
$ javac Cat.java
Préparez un fichier texte.
$ cat sample.txt 
échantillon
échantillon
SANNPURU
Exécutez l'exemple de code.
$ java Cat sample.txt 
échantillon
échantillon
SANNPURU
échantillon
échantillon
SANNPURU
échantillon
échantillon
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
--Référence anglaise
Référence japonaise
Recommended Posts