我的目的是重命名一个文件。我正在做的是:我在一个文本文件中搜索一个特定的字符串。在这么多文件中,如果找到了特定的文本,那么我想用给定的字符串重命名该文本文件。
这是我尝试过的:
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();
}
}
}
上面的代码正在搜索特定文件。但我无法重命名它。
这个问题的有效解决方案是什么?