我想读入一个文件,并用新文本替换一些文本。使用asm和int 21h会很简单,但我想使用新的java8流。
Files.write(outf.toPath(),
(Iterable<String>)Files.lines(inf)::iterator,
CREATE, WRITE, TRUNCATE_EXISTING);在那里的某个地方我想要一台lines.replace("/*replace me*/","new Code()\n");。新的代码行是因为我想测试在什么地方插入一段代码。
这里有一个播放示例,它不能按照我想要的方式工作,但可以编译。我只需要一种方法来截取迭代器中的行,并用代码块替换某些短语。
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import static java.nio.file.StandardOpenOption.*;
import java.util.Arrays;
import java.util.stream.Stream;
public class FileStreamTest {
public static void main(String[] args) {
String[] ss = new String[]{"hi","pls","help","me"};
Stream<String> stream = Arrays.stream(ss);
try {
Files.write(Paths.get("tmp.txt"),
(Iterable<String>)stream::iterator,
CREATE, WRITE, TRUNCATE_EXISTING);
} catch (IOException ex) {}
//// I'd like to hook this next part into Files.write part./////
//reset stream
stream = Arrays.stream(ss);
Iterable<String> it = stream::iterator;
//I'd like to replace some text before writing to the file
for (String s : it){
System.out.println(s.replace("me", "my\nreal\nname"));
}
}
}编辑:我已经走到这一步了,它起作用了。我正在尝试使用过滤器,也许这并不是必须的。
Files.write(Paths.get("tmp.txt"),
(Iterable<String>)(stream.map((s) -> {
return s.replace("me", "my\nreal\nname");
}))::iterator,
CREATE, WRITE, TRUNCATE_EXISTING);发布于 2015-02-20 05:48:55
Files.write(..., Iterable, ...)方法在这里看起来很诱人,但将Stream转换为Iterable会使这变得很麻烦。它还从Iterable中“拉出”,这有点奇怪。如果文件写入方法可以用作流的终端操作,比如forEach,那会更有意义。
不幸的是,大多数编写的代码都抛出了IOException,这是forEach所期望的Consumer函数接口所不允许的。但是PrintWriter是不同的。至少,它的编写方法不会抛出检查过的异常,尽管打开一个异常仍然可以抛出IOException。下面是它的使用方法。
Stream<String> stream = ... ;
try (PrintWriter pw = new PrintWriter("output.txt", "UTF-8")) {
stream.map(s -> s.replaceAll("foo", "bar"))
.forEachOrdered(pw::println);
}注意forEachOrdered的使用,它以读取输出行的相同顺序打印输出行,这大概就是您想要的!
如果您正在从输入文件中读取行,修改它们,然后将它们写入输出文件,那么将这两个文件放在同一try-with-resources语句中是合理的:
try (Stream<String> input = Files.lines(Paths.get("input.txt"));
PrintWriter output = new PrintWriter("output.txt", "UTF-8"))
{
input.map(s -> s.replaceAll("foo", "bar"))
.forEachOrdered(output::println);
}https://stackoverflow.com/questions/28504504
复制相似问题