Java流API:修改文件中的特定行

发布于 2025-02-01 16:10:41 字数 1380 浏览 3 评论 0原文

我正在阅读readme文件的内容作为字符串列表

,我想修改此文件的特定行(因此列表的特定字符串)。

我设法实现了它,但是有没有(仅)Java流操作(就像我目前正在学习Java Stream API)的优雅方法?

我发现的其他代码显示了如何创建新列表并在执行replaceAll()或附加某些字符之后,将新字符串添加到此列表中。

我的情况有些不同,我只想更改我在文件中发现的一条线(更具体地说是它的某些字符,即使我可以重新编写整个行)。 目前,我只是在新列表中一一重写所有行,除了我生成和编写的一行(所以我想修改的行)。

我对这样做的任何方式都开放,我可以更改I/O类型,重写整个文件/行,或者只是更改其中的一部分...只要我最终获得了修改后的readme文件。只是寻找这样做的“流方式”。

我的实际代码:

private static List<String> getReadme() {
  try {
    return stream(readFileToString(new File("readme.md")).split("\n")).collect(Collectors.toList());
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}

public static void generateReadMe(String day, String year, int part) {
  List<String> readme = getReadme();

  // hidden code where I create the line I want to end up modified...
  String line = prefix + fDay + stars + color + packages + fYear + "/days/Day"+ day +".java)\n";

  List<String> newReadme = readme.stream().map(l -> {
    if (l.contains(fYear) && l.contains(fDay)) {
      // add the modified line (aka replacing the line)
      return line;
    } else {
      // or add the non modified line if not the one we're looking for
      return l;
    }
  }).toList();

  newReadme.forEach(System.out::println);
}

I am reading the content of a readme file as a list of strings

And I want to modify a specific line of this file (so a specific string of the list).

I managed to achieve it, but is there an elegant way to do this with (only) java stream operations (as I am currently learning the java Stream API)?

Other code I found showed how to create a new List and add new strings to this list after performing a replaceAll() or appending certain characters.

My case is a bit different, and I'd like to change only a certain line I am finding in the file (and more specifically certain characters of it, even though I am fine with re-writing the whole line).
For now, I just re-write all lines one by one in a new list, except for one line that I generate and write instead (so the line I wanted to modify).

I'm open to any way of doing so, I can change the i/o types, re-write the whole file/line or just change a part of it... as long as I end up with a modified readme file. Just looking for a "stream way" of doing so.

My actual code:

private static List<String> getReadme() {
  try {
    return stream(readFileToString(new File("readme.md")).split("\n")).collect(Collectors.toList());
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}

public static void generateReadMe(String day, String year, int part) {
  List<String> readme = getReadme();

  // hidden code where I create the line I want to end up modified...
  String line = prefix + fDay + stars + color + packages + fYear + "/days/Day"+ day +".java)\n";

  List<String> newReadme = readme.stream().map(l -> {
    if (l.contains(fYear) && l.contains(fDay)) {
      // add the modified line (aka replacing the line)
      return line;
    } else {
      // or add the non modified line if not the one we're looking for
      return l;
    }
  }).toList();

  newReadme.forEach(System.out::println);
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

风月客 2025-02-08 16:10:41

您不需要apache commons,我建议使用files.lines java.nio.file.files.files,您也可以使用下面的实现一种方法

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Example {

    public static void generateReadMe(String day, String year, int part) {
        List<String> newReadme = null;

        try (Stream<String> lines = Files.lines(Paths.get("readme.md"))) {
             newReadme = lines.map(l -> l.contains(fYear) && l.contains(fDay) ? replaceLine() : l).collect(Collectors.toList())
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        newReadme.forEach(System.out::println);
    }

    private static String replaceLine() {
        //Your implementation
        return prefix + fDay + stars + color + packages + fYear + "/days/Day" + day + ".java)\n";
    }

}

You wouldn't need Apache commons, I'd suggest using Files.lines of java.nio.file.Files, also you can have the implementation one single method like below

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Example {

    public static void generateReadMe(String day, String year, int part) {
        List<String> newReadme = null;

        try (Stream<String> lines = Files.lines(Paths.get("readme.md"))) {
             newReadme = lines.map(l -> l.contains(fYear) && l.contains(fDay) ? replaceLine() : l).collect(Collectors.toList())
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        newReadme.forEach(System.out::println);
    }

    private static String replaceLine() {
        //Your implementation
        return prefix + fDay + stars + color + packages + fYear + "/days/Day" + day + ".java)\n";
    }

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文