【发布时间】:2015-04-14 18:49:38
【问题描述】:
我想读入一个文件并用新文本替换一些文本。使用 asm 和 int 21h 会很简单,但我想使用新的 java 8 流。
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);
【问题讨论】:
-
我很困惑。您想从文件中读取一些文本行,将这些行替换为其他一些文本(可能通过正则表达式),然后将这些行写回文件?对吗?
-
没错。也许我会在问题中更好地解释。
标签: java-8 java-stream