我的目的是重命名一个文件。我正在做的是:我正在文本文件中搜索特定字符串。在如此多的文件中,如果找到特定的文本,那么我想用给定的字符串重命名该文本文件。
这是我尝试过的:
String opcode="OPCODES"; // String that I want to search.
File file = new File("D:\\CFF1156"); // All files are inside this folder.
System.out.println("The File Name is :"+file.getName());
File[] f = file.listFiles();
System.out.println("The Length of File is :"+f.length);
Boolean flag=false;
StringBuffer contents = new StringBuffer();
BufferedReader reader = null;
for(int i=0;i<f.length;i++)
{
try{
reader = new BufferedReader(new FileReader(f[i]));
String text = null;
while ((text = reader.readLine()) != null)
{
if(text.contains(opcode))
{
System.out.println("Found");
System.out.println("The File Containing the Search text is :"+f[i]);
f[i].renameTo(new File("D://CFF1156/changed.txt"));
System.out.println("renamed :"+(f[i].renameTo(new File("D://CFF1156/changed.txt"))));
if(f[i].renameTo(new File("D://CFF1156/changed.txt")))
{
System.out.println("Successfully renamed");
}
else
{
System.out.println("Error");
}
}
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
finally
{
try
{
if (reader != null)
{
reader.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
上面的代码正在搜索特定的文件。但我无法重命名它。
这个问题的有效解决方案是什么?
最佳答案
您正在循环中使用相同的名称进行重命名。先解决那个问题吧此外,通过 renameTo()
方法获取变量中返回的 boolean
值,并在 if
中使用该变量。
关于java - 如何在 Java 中重命名文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1713522/