在多个Java文件中重写数据
经过大量的研究后,我找到了使用正则表达式在文件中重新写入数据的代码,但是我被如何重新修改我的代码所困扰,以便在充满文本文件的目录中读取数据,查找正则表达式模式并用我想要的文本替换它。我在做这方面是新的任何帮助将不胜感激这是我到目前为止,在每个文件的基础上的工作在多个Java文件中重写数据,java,file,Java,File,经过大量的研究后,我找到了使用正则表达式在文件中重新写入数据的代码,但是我被如何重新修改我的代码所困扰,以便在充满文本文件的目录中读取数据,查找正则表达式模式并用我想要的文本替换它。我在做这方面是新的任何帮助将不胜感激这是我到目前为止,在每个文件的基础上的工作 Path path = Paths.get("C:\\Users\\hoflerj\\Desktop\\After\\test.txt"); Charset charset = StandardCharsets.UTF_8; String
Path path = Paths.get("C:\\Users\\hoflerj\\Desktop\\After\\test.txt");
Charset charset = StandardCharsets.UTF_8;
String content = new String(Files.readAllBytes(path), charset);
content = content.replaceAll("2018(.+)", "XXXX");
Files.write(path, content.getBytes(charset));
几个月前,我创建了一些代码,读取文件名,查找模式,并缩短名称长度。看起来我应该做一些类似的事情,但我不能把它们放在一起。代码如下
for (File file:filesInDir) {
//x++;
String name = file.getName();
String newName = name;
//String sameName = name;
if (name.contains("LABEL")){
newName = name.replaceAll("\\-2018(.+)\\d", "") ;
System.out.println(newName); // prints prints to file
String newPath = absolutePathOne + "\\" + newName;
file.renameTo(new File(newPath));
//Files.move(file.toPath(), Paths.get(newPath));
}
if (!name.contains("LABEL")){
newName = name.replaceAll("\\-2018(.+)", "");
System.out.println(newName); // prints prints to file
String newPath = absolutePathOne + "\\" + newName +".txt";
file.renameTo(new File(newPath));
//Files.move(file.toPath(), Paths.get(newPath));
}
}
请帮我把这些点连起来。同样,我的目标是循环遍历目录中的所有文件,找到模式并用我喜欢的文本替换模式。Java7文件API有许多有用的方法来实现您的目标。例如,有一种方法允许您迭代文件夹中的所有文件。要读取、写入和重命名文件,分别有、和方法 所以你可以试试这样的东西:
String folderPath = "/your/path";
String contentRegexp = "2018(.+)";
String contentReplacement = "XXXX";
String filenameRegexp = "-2018(.+)\\d";
String filenameReplacement = "";
// 1 is a maximum depth of traversal;
// you can use it if you have any subdirectories wich you want to process too
try (Stream<Path> paths = Files.walk(Paths.get(folderPath), 1)) {
// filtering only files
paths.filter(file -> Files.isRegularFile(file))
.forEach(file -> {
try {
//reading all lines and replacing content in each line
List<String> lines = Files.readAllLines(file)
.stream()
.map(s -> s.replaceAll(contentRegexp, contentReplacement))
.collect(Collectors.toList());
//writing lines back
Files.write(file, lines, StandardOpenOption.WRITE,
StandardOpenOption.TRUNCATE_EXISTING);
//renaming file
Files.move(file, file.resolveSibling(file.getFileName()
.toString()
.replaceAll(filenameRegexp, filenameReplacement)));
} catch (IOException e) {
e.printStackTrace();
}
});
}
但是在这里使用正则表达式时要小心:2018。+将用'XXXX'替换'2018'及其后的所有字符串。谢谢,我将尝试这样做!:问题:如果我不想要一个文件名过滤器,没有它能工作吗?我不在乎文件名是什么,我希望不管文件名是什么,它都能这样做。@Jonathan当然可以,您只需要从筛选条件中删除&&file.getFileName.toString.containsfileNameFilter。问题是,是否有办法将contentRegexp限制为仅第一次出现?我用我的regex在线工具对此进行了研究,这是我能想到的最接近2018年[^]**\d@JonathanHofler您的实际字符串是什么样子的?您希望替换它的哪个部分?