今天为了给文件重新命名,怎么着也不能成功
if(f.renameTo(new File(path + "/" +newname)))
System.out.println(path + "/" +newname + "has renamed");
后来各种百度,有说文件名不能带变量的,有说地址不能出现“_” "-" ":"等符号的,我都试了,最后发现时因为我之前用到的BefferedReader进行读操作之后,没有关闭,导致不能重新命名,但是比较蛋疼的就是他并没有报错,就是不能重新命名,最后我把BefferedReader关了就好使了
函数如下
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class stringtest {
public static void main(String args[]) throws IOException, FileNotFoundException{
String[] keywords={"事故","死亡","受伤","失踪","损失","伤亡","灾区","救灾","灾害","受灾","救灾","救援"}; //事故关键字
int wordCount = 0; //一共多少起带关键字的文件
String path = "D:/renminribaoData/from1to10000"; //文件夹地址
File file = new File(path);
String fileNames[] = file.list();
for(int i = 0 ;i< 5;i++){
BufferedReader br = new BufferedReader(new FileReader(path + "/" + fileNames[i]));
System.out.println("正在匹配" + fileNames[i]); //读取BufferedRead的内容称String型
String temp = "";
String s = "";
String newname = "";
while((temp = br.readLine()) != null)
{
s = s + temp;
}
for(int j = 0 ; j < keywords.length; j++){
if(s.contains(keywords[j])){
System.out.println(fileNames[i] + "含有关键字");
File f = new File(path + "/" + fileNames[i]);
// System.out.println(path + "\\" + fileNames[i]);
// if(!fileNames[i].contains("Y_")) System.out.println("exist!");
// else System.out.println("no!");
// br.close(); 就是这个地方 一定不能忘记关掉啊
if(f.exists()&& !fileNames[i].contains("Y") )
newname = "Y" + fileNames[i];
System.out.println(newname);
if(f.renameTo(new File(path + "/" +newname)))
System.out.println(path + "/" +newname + "has renamed");
wordCount++;
break;
}
else{
//如果不带关键字进行的操作
}
}
}
System.out.println("一共有" + wordCount + "个带有关键字的文件");
}
}