我正在将我编写的java for循环转换为java流,for循环具有我认为可以用流修复的重复代码,这就是我在旧循环中所做的事情。
try (DirectoryStream<Path> stream = Files.newDirectoryStream(path)) {
for (Path entry : stream) {
String fileName = entry.getFileName().toString();
if (Files.isDirectory(entry)) {
grepFilesAndFolders(entry);
} else if (shouldChange(entry)) {
//Doing all the foreach work here
}
}
}
}
这是我目前在我的信息流中拥有的
Files.walk(path)
.filter(this::shouldChange)
.forEach(p -> {
try {
String fileName = p.getFileName().toString();
Charset charset = StandardCharsets.UTF_8;
String content = new String(Files.readAllBytes(p), charset);
boolean contentChanged = false;
int count = countMatches(content, getName(oldName, '1'));
if (count > 0) {
content = replaceName(count,
getName(oldName, '1'),
fileName,
getName(newName, '1'),
content);
contentChanged = true;
}
count = countMatches(content, getName(oldName, '2'));
if (count > 0) {
content = replaceName(count,
getName(oldName, '2'),
fileName,
getName(newName, '2'), content);
contentChanged = true;
}
if (contentChanged) {
Files.write(p, content.getBytes(charset));
}
} catch (IOException e) {
e.printStackTrace();
}
});
我想做的是尝试摆脱下面的重复代码。
int count = countMatches(content, getName(oldName, '1'));
if (count > 0) {
content = replaceName(count,
getName(oldName, '1'),
fileName,
getName(newName, '1'),
content);
contentChanged = true;
}
count = countMatches(content, getName(oldName, '2'));
if (count > 0) {
content = replaceName(count,
getName(oldName, '2'),
fileName,
getName(newName, '2'), content);
contentChanged = true;
}
if (contentChanged) {
Files.write(p, content.getBytes(charset));
}
我所能做的就是在新方法中进行替换,然后将其map
替换为流,但是那样我就无法对contentChanged
变量进行处理了。但是我不知道该怎么做,到目前为止,我只布置了流和过滤器。
答案 0 :(得分:0)
for (char i = '1'; i < '3'; ++i) {
int count = countMatches(content, getName(oldName, i));
if (count > 0) {
content = replaceName(count,
getName(oldName, i),
fileName,
getName(newName, i),
content);
contentChanged = true;
}
}
答案 1 :(得分:0)
private String replaceName(String content, String fileName, char ch) {
if (countMatches(content, getName(oldName, ch)) > 0)
content = replaceName(count, getName(oldName, ch), fileName, getName(newName, ch), content);
return content;
}
Files.walk(path)
.filter(this::shouldChange)
.forEach(p -> {
try {
String fileName = p.getFileName().toString();
final String content = new String(Files.readAllBytes(p), StandardCharsets.UTF_8);
String changedContent = replaceName(content, fileName, '1');
changedContent = replaceName(content, fileName, '2');
if (!content.equals(changedContent))
Files.write(p, content.getBytes(StandardCharsets.UTF_8));
} catch(IOException e) {
e.printStackTrace();
}
});
}