Java 我试图修改文本文件中的一些行,当我再次将该行写回文件时,最终得到一个空白文件
这段代码正在读取大量的.java文件,找到“public[classname]”或“private[classname]”,并在该行中添加“System.out.println([classname]) 问题是,当我把那一行写回时,结果是一个空白文件 有人能看出我做错了什么吗Java 我试图修改文本文件中的一些行,当我再次将该行写回文件时,最终得到一个空白文件,java,Java,这段代码正在读取大量的.java文件,找到“public[classname]”或“private[classname]”,并在该行中添加“System.out.println([classname]) 问题是,当我把那一行写回时,结果是一个空白文件 有人能看出我做错了什么吗 private static void work(ArrayList<File> fileList) { for (int i = 0; i < fileList.size(); i++) {
private static void work(ArrayList<File> fileList) {
for (int i = 0; i < fileList.size(); i++) {
replaceLines(fileList.get(i));
}
}
public static void replaceLines(File file) {
String path = file.getPath();
String fileNameLong = file.getName();
String fileName = null;
if (fileNameLong.contains(".java")) {
fileName = fileNameLong.substring(0, file.getName().indexOf("."));
}
if (fileName != null && fileName != "") {
System.out.println(fileName);
try {
//prepare reading
FileInputStream in = new FileInputStream(path);
BufferedReader br = new BufferedReader(
new InputStreamReader(in));
//prepare writing
FileWriter fw = new FileWriter(file);
PrintWriter out = new PrintWriter(fw);
String strLine;
while ((strLine = br.readLine()) != null) {
// Does it contain a public or private constructor?
boolean containsPrivateCon = strLine.contains("private "
+ fileName);
boolean containsPublicCon = strLine.contains("public "
+ fileName);
if (containsPrivateCon || containsPublicCon) {
int lastIndexOfBrack = strLine.lastIndexOf("{");
while (lastIndexOfBrack == -1) {
strLine = br.readLine();
lastIndexOfBrack = strLine.lastIndexOf("{");
}
if (lastIndexOfBrack != -1) {
String myAddition = "\n System.out.println(\""
+ fileName + ".java\"); \n";
String strLineModified = strLine.substring(0,
lastIndexOfBrack + 1)
+ myAddition
+ strLine.substring(lastIndexOfBrack + 1);
strLine = strLineModified;
}
}
out.write(strLine);
}
} catch (Exception e) {
System.out.println(e);
}
}
}
私有静态无效工作(ArrayList文件列表){
对于(int i=0;i
您忘记刷新并关闭文件。PrintWriter
保留一个缓冲区,除非您明确地flush()
它,否则数据将(取消)愉快地位于缓冲区中,并且永远不会写入输出
因此,您需要在catch(异常e){
请注意,这仅对
PrintWriter
和PrintStream
是必需的。所有其他输出类在关闭时都会刷新。如果要写入正在读取的同一文件,则应写入该文件的副本(不同的文件名)然后重命名输出文件,或使用界面在位编辑文件
通常,第一种解决方案比第二种解决方案更容易实现;除非文件很大(可能不是.java文件的情况),否则没有真正的理由使用第二种解决方案。我刚刚在
out.write()之后添加了这一点
但我仍然得到空白文件在调试器中运行代码,以确保您确实向文件写入了任何内容。而且,正如ono15所说,您应该向新文件写入内容,而不是覆盖输入文件。
out.flush();
out.close();