ストリームとファイルI/O

ストリームは、JDK 8から導入されたAPI(java.util.stream)で、コレクションや配列のデータを操作するために使用されます。このAPIはLambda式を大量に利用しており、コードが簡潔になり可読性が向上します。

ストリームの使用方法は以下の通りです。まず、データソースを取得し、そのストリームを取得します。その後、ストリーム内の様々なメソッドを使用してデータを処理し、最終的に結果を得ます。

1.1 ストリームの取得

public static void main(String[] args) {
    // Listからストリームを取得
    List<String> names = Arrays.asList("張さんぼう", "張むきつ", "シウジろ", "タミ", "張きょう");
    Stream<String> stream = names.stream();

    // Setからストリームを取得
    Set<String> set = new HashSet<>(Arrays.asList("リュウデカワ", "チャンマム", "スパイダーじん", "バッデ", "デマシア"));
    Stream<String> stream1 = set.stream();
    stream1.filter(s -> s.contains("デ")).forEach(System.out::println);

    // Mapからストリームを取得
    Map<String, Double> map = new HashMap<>();
    map.put("コリナザ", 172.3);
    map.put("ディリホットバ", 168.3);
    map.put("マルサハ", 166.3);
    map.put("カルサバ", 168.3);

    Stream<Map.Entry<String, Double>> entryStream = map.entrySet().stream();
    entryStream.filter(e -> e.getKey().contains("バ"))
            .forEach(e -> System.out.println(e.getKey() + "-->" + e.getValue()));

    // 配列からストリームを取得
    String[] namesArray = {"チャンサイ", "トウダイサン", "ドキュキュウハイ", "ドクゴキュウハイ"};
    Stream<String> arrayStream1 = Arrays.stream(namesArray);
    Stream<String> arrayStream2 = Stream.of(namesArray);
}

1.2 ストリームの中間操作

中間操作は呼び出された後、新しいストリームを返すため、チェーンで続けて使用できます。

public static void main(String[] args) {
    List<Double> scores = Arrays.asList(88.5, 100.0, 60.0, 99.0, 9.5, 99.6, 25.0);
    // 成績が60点以上のものを昇順に出力
    scores.stream().filter(score -> score >= 60).sorted().forEach(System.out::println);

    List<Student> students = new ArrayList<>();
    students.add(new Student("スパイダーじん", 26, 172.5));
    students.add(new Student("ツーシャ", 23, 167.6));
    students.add(new Student("ハクシンシン", 25, 169.0));
    students.add(new Student("ニューモウコウ", 35, 183.3));
    students.add(new Student("ニューフォン", 34, 168.5));
    // 年齢が23歳以上30歳以下の人を年齢順に出力
    students.stream().filter(student -> student.getAge() >= 23 && student.getAge() <= 30)
            .sorted(Comparator.comparingInt(Student::getAge).reversed())
            .forEach(System.out::println);

    // 最も高い3人の学生を出力
    students.stream().sorted(Comparator.comparingDouble(Student::getHeight).reversed())
            .limit(3).forEach(System.out::println);

    // 最も低い2人の学生を出力
    students.stream().sorted(Comparator.comparingDouble(Student::getHeight).reversed())
            .skip(students.size() - 2).forEach(System.out::println);

    // 高さが168cm以上の学生の名前を重複なく出力
    students.stream().filter(student -> student.getHeight() > 168)
            .map(Student::getName).distinct().forEach(System.out::println);

    Stream<String> stream1 = Stream.of("サナ", "リシ");
    Stream<String> stream2 = Stream.of("サナ2", "リシ2", "ゴウゴ");
    Stream<String> combinedStream = Stream.concat(stream1, stream2);
    combinedStream.forEach(System.out::println);
}

1.3 終端操作

終端操作では、ストリームをコレクションや配列に戻すことができます。

public static void main(String[] args) {
    List<Student> students = new ArrayList<>();
    students.add(new Student("スパイダーじん", 26, 172.5));
    students.add(new Student("ツーシャ", 23, 167.6));
    students.add(new Student("ハクシンシン", 25, 169.0));
    students.add(new Student("ニューモウコウ", 35, 183.3));
    students.add(new Student("ニューフォン", 34, 168.5));
    // 高さが168cm以上の学生の人数を出力
    long count = students.stream().filter(student -> student.getHeight() > 168).count();
    System.out.println(count);

    // 最も高い学生を出力
    Optional<Student> tallest = students.stream().max(Comparator.comparingDouble(Student::getHeight));
    tallest.ifPresent(System.out::println);

    // 最も低い学生を出力
    Optional<Student> shortest = students.stream().min(Comparator.comparingDouble(Student::getHeight));
    shortest.ifPresent(System.out::println);

    // 高さが170cm以上の学生をリストとして取得
    List<Student> tallStudents = students.stream().filter(student -> student.getHeight() > 170).collect(Collectors.toList());
    System.out.println(tallStudents);

    // 高さが170cm以上の学生をセットとして取得
    Set<Student> tallStudentsSet = students.stream().filter(student -> student.getHeight() > 170).collect(Collectors.toSet());
    System.out.println(tallStudentsSet);

    // 高さが170cm以上の学生の名前と高さをマップとして取得
    Map<String, Double> heightMap = students.stream().filter(student -> student.getHeight() > 170)
            .collect(Collectors.toMap(Student::getName, Student::getHeight));
    System.out.println(heightMap);

    // 高さが170cm以上の学生を配列として取得
    Student[] tallStudentsArray = students.stream().filter(student -> student.getHeight() > 170).toArray(Student[]::new);
    System.out.println(Arrays.toString(tallStudentsArray));
}

2. ファイル操作

Fileクラスは、java.ioパッケージに含まれており、ファイルやディレクトリを表します。Fileクラスを使用することで、ファイルの情報を取得したり、ファイルを作成したりすることができます。

2.1 Fileオブジェクトの作成

public static void main(String[] args) {
    File file1 = new File("D:" + File.separator + "resource" + File.separator + "ab.txt");
    System.out.println(file1.length());

    File file2 = new File("D:/resource");
    System.out.println(file2.length());

    File file3 = new File("D:/resource/aaaa.txt");
    System.out.println(file3.length());
    System.out.println(file3.exists());

    File file4 = new File("file-io-app/src/itheima.txt");
    System.out.println(file4.length());
}

2.2 Fileの一般的なメソッド

public static void main(String[] args) throws Exception {
    File file1 = new File("D:/resource/itheima2.txt");
    System.out.println(file1.createNewFile());

    File file2 = new File("D:/resource/aaa");
    System.out.println(file2.mkdir());

    File file3 = new File("D:/resource/bbb/ccc/ddd/eee/fff/ggg");
    System.out.println(file3.mkdirs());

    System.out.println(file1.delete());
    System.out.println(file2.delete());
    File file4 = new File("D:/resource");
    System.out.println(file4.delete());
}

2.3 ディレクトリの走査

public static void main(String[] args) {
    File directory = new File("D:\\course\\待開発コンテンツ");
    String[] names = directory.list();
    for (String name : names) {
        System.out.println(name);
    }

    File[] files = directory.listFiles();
    for (File file : files) {
        System.out.println(file.getAbsolutePath());
    }

    File file = new File("D:/resource/aaa");
    File[] files1 = file.listFiles();
    System.out.println(Arrays.toString(files1));
}

2.4 ファイル検索

public class SearchTest {
    public static void main(String[] args) throws Exception {
        searchFile(new File("D:/"), "QQ.exe");
    }

    public static void searchFile(File dir, String fileName) throws Exception {
        if (dir == null || !dir.exists() || dir.isFile()) {
            return;
        }

        File[] files = dir.listFiles();
        if (files != null && files.length > 0) {
            for (File f : files) {
                if (f.isFile()) {
                    if (f.getName().contains(fileName)) {
                        System.out.println("見つかりました: " + f.getAbsolutePath());
                        Runtime runtime = Runtime.getRuntime();
                        runtime.exec(f.getAbsolutePath());
                    }
                } else {
                    searchFile(f, fileName);
                }
            }
        }
    }
}

3. I/Oストリーム

I/Oストリームはデータの読み書きを行うためのもので、ファイルやネットワークからのデータを扱います。

3.1 FileInputStream(ファイルのバイト入力ストリーム)

public static void main(String[] args) throws Exception {
    InputStream inputStream = new FileInputStream("test.txt");
    int b;
    while ((b = inputStream.read()) != -1) {
        System.out.print((char) b);
    }

    byte[] buffer = new byte[3];
    int length;
    while ((length = inputStream.read(buffer)) != -1) {
        String result = new String(buffer, 0, length);
        System.out.print(result);
    }

    inputStream.close();
}

3.2 FileOutputStream(ファイルのバイト出力ストリーム)

public static void main(String[] args) throws Exception {
    OutputStream outputStream = new FileOutputStream("test1.txt", true);
    outputStream.write(97);
    outputStream.write('b');

    byte[] bytes = "私はあなたを愛していますabc".getBytes();
    outputStream.write(bytes);

    outputStream.write(bytes, 0, 15);
    outputStream.write("\r\n".getBytes());

    outputStream.close();
}

3.3 FileReader(ファイルのキャラクタ入力ストリーム)

public static void main(String[] args)  {
    try (Reader reader = new FileReader("io-app2/src/itheima01.txt")) {
        char[] buffer = new char[3];
        int length;
        while ((length = reader.read(buffer)) != -1) {
            System.out.print(new String(buffer, 0, length));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

3.4 FileWriter(ファイルのキャラクタ出力ストリーム)

public static void main(String[] args) {
    try (Writer writer = new FileWriter("io-app2/src/itheima02out.txt", true)) {
        writer.write('a');
        writer.write(97);
        writer.write("\r\n");

        writer.write("私はあなたを愛していますabc");
        writer.write("\r\n");

        writer.write("私はあなたを愛していますabc", 0, 5);
        writer.write("\r\n");

        char[] buffer = {'ヒ', 'マ', 'a', 'b', 'c'};
        writer.write(buffer);
        writer.write("\r\n");

        writer.write(buffer, 0, 2);
        writer.write("\r\n");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

3.5 バッファリングストリーム

3.5.1 バイトバッファリングストリーム(BufferedInputStream, BufferedOutputStream)

public static void main(String[] args) {
    try (
            InputStream inputStream = new FileInputStream("io-app2/src/itheima01.txt");
            InputStream bufferedInputStream = new BufferedInputStream(inputStream);

            OutputStream outputStream = new FileOutputStream("io-app2/src/itheima01_bak.txt");
            OutputStream bufferedOutputStream = new BufferedOutputStream(outputStream)
    ) {
        byte[] buffer = new byte[1024];
        int length;
        while ((length = bufferedInputStream.read(buffer)) != -1) {
            bufferedOutputStream.write(buffer, 0, length);
        }
        System.out.println("コピー完了!!");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

3.5.2 キャラクタバッファリング入力ストリーム(BufferedReader)

public static void main(String[] args)  {
    try (
            Reader reader = new FileReader("io-app2/src/itheima04.txt");
            BufferedReader bufferedReader = new BufferedReader(reader)
    ) {
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            System.out.println(line);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

3.5.3 キャラクタバッファリング出力ストリーム(BufferedWriter)

public static void main(String[] args) {
    try (
            Writer writer = new FileWriter("io-app2/src/itheima05out.txt", true);
            BufferedWriter bufferedWriter = new BufferedWriter(writer)
    ) {
        bufferedWriter.write('a');
        bufferedWriter.write(97);
        bufferedWriter.write('磊');
        bufferedWriter.newLine();

        bufferedWriter.write("私はあなたを愛していますabc");
        bufferedWriter.newLine();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

3.6 変換ストリーム

3.6.1 InputStreamReader(キャラクタ入力変換ストリーム)

public static void main(String[] args) {
    try (
            InputStream inputStream = new FileInputStream("io-app2/src/itheima06.txt");
            Reader inputStreamReader = new InputStreamReader(inputStream, "GBK");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader)
    ) {
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            System.out.println(line);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

3.6.2 OutputStreamWriter(キャラクタ出力変換ストリーム)

public static void main(String[] args) {
    try (
            OutputStream outputStream = new FileOutputStream("io-app2/src/itheima07out.txt");
            Writer outputStreamWriter = new OutputStreamWriter(outputStream, "GBK");
            BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter)
    ) {
        bufferedWriter.write("私は中国人abc");
        bufferedWriter.write("私はあなたを愛しています123");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

3.7 プリンターストリーム(PrintStream/PrintWriter)

3.7.1 PrintStream

public static void main(String[] args) {
    try (
            PrintWriter printWriter = new PrintWriter(new FileOutputStream("io-app2/src/itheima08.txt", true))
    ) {
        printWriter.print(97);
        printWriter.print('a');
        printWriter.println("私はあなたを愛していますabc");
        printWriter.println(true);
        printWriter.println(99.5);

        printWriter.write(97);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

3.7.2 PrintWriter

public static void main(String[] args) {
    System.out.println("老骥伏枥");
    System.out.println("志在千里");

    try (PrintStream printStream = new PrintStream("io-app2/src/itheima09.txt")) {
        System.setOut(printStream);

        System.out.println("烈士暮年");
        System.out.println("壮心不已");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

3.8 データストリーム

3.8.1 DataOutputStream(データ出力ストリーム)

public static void main(String[] args) {
    try (
            DataOutputStream dataOutputStream = new DataOutputStream(new FileOutputStream("io-app2/src/itheima10out.txt"))
    ) {
        dataOutputStream.writeInt(97);
        dataOutputStream.writeDouble(99.5);
        dataOutputStream.writeBoolean(true);
        dataOutputStream.writeUTF("黑马プログラマー666!");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

3.8.2 DataInputStream(データ入力ストリーム)

public static void main(String[] args) {
    try (
            DataInputStream dataInputStream = new DataInputStream(new FileInputStream("io-app2/src/itheima10out.txt"))
    ) {
        int integer = dataInputStream.readInt();
        System.out.println(integer);

        double doubleValue = dataInputStream.readDouble();
        System.out.println(doubleValue);

        boolean booleanValue = dataInputStream.readBoolean();
        System.out.println(booleanValue);

        String string = dataInputStream.readUTF();
        System.out.println(string);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

3.9 シリアライズストリーム

3.9.1 ObjectOutputStream(オブジェクトバイト出力ストリーム)

public static void main(String[] args) {
    try (
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("io-app2/src/itheima11out.txt"))
    ) {
        User user = new User("admin", "張さん", 32, "666888xyz");
        objectOutputStream.writeObject(user);
        System.out.println("オブジェクトのシリアライズ成功!!");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

3.9.2 ObjectInputStream(オブジェクトバイト入力ストリーム)

public static void main(String[] args) {
    try (
            ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("io-app2/src/itheima11out.txt"))
    ) {
        User user = (User) objectInputStream.readObject();
        System.out.println(user);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

4. I/Oフレームワーク

フレームワークは、Javaが提供するファイルやデータ操作コードをカプセル化し、より簡単にファイルを操作できるようにします。

4.1 Commons-io

Commons-ioはApacheによって提供されるフレームワークで、IO操作の効率を向上させます。

タグ: Java Stream File I/O Commons-io

6月13日 20:09 投稿