[英]Java - Renaming a file automatically after searching a directory
When I run this program, it finds the file that starts with yyyy and returns the files correctly; 当我运行该程序时,它会找到以yyyy开头的文件并正确返回文件; however, it skips my.File.exists() and goes to else "File Name Change Failed". 但是,它会跳过my.File.exists()并转到其他“文件名更改失败”。 I have been looking at this code for a long time..what noob mistake am I making? 我一直在看这段代码很久了..我到底犯了什么错误?
//Searches the path for files
String pathToScan =("C:\\Users\\desktop\\test\\");
String target_file ;
File folderToScan = new File(pathToScan);
File[] listOfFiles = folderToScan.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
target_file = listOfFiles[i].getName();
if (target_file.startsWith("YYYY")){
System.out.println("-----------------------------------------------");
System.out.println("Match Found: "+ target_file);
//if the target file exists
if(myFile.exists()){
long lastmod = myFile.lastModified();
SimpleDateFormat format = new SimpleDateFormat("YYYY-MM-DD");
String lastmodi = format.format(new Date(lastmod));
File newfile = new File("C:\\Users\\desktop\\test\\"+lastmodi+".csv");
//If rename successful, then print success with file location
if(myFile.renameTo(newfile)){
System.out.println("File Name Change Successful, New File Created:" + newfile.getPath());
}
else{
System.out.println("File Name Change Failed");
}
}
I think you are referring a wrong file in myFile
. 我认为您在myFile
中引用了错误的文件。 The following code is working for me with added code. 以下代码对我有用,并添加了代码。 The other reasons can be that you don't have the Access to Write in C:\\Users\\desktop\\test\\ directory and/or that directory doesn't exist. 另一个原因可能是您没有C:\\ Users \\ desktop \\ test \\目录中的“写访问权限”和/或该目录不存在。
String pathToScan = ("C:\\Users\\<User Name>\\desktop\\test\\");
String target_file;
File folderToScan = new File(pathToScan);
File myFile = null; // Added this
File[] listOfFiles = folderToScan.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
target_file = listOfFiles[i].getName();
myFile = listOfFiles[i]; // Added this
if (target_file.startsWith("YYYY")) {
System.out
.println("-----------------------------------------------");
System.out.println("Match Found: " + target_file);
// if the target file exists
if (myFile.exists()) {
long lastmod = myFile.lastModified();
SimpleDateFormat format = new SimpleDateFormat(
"YYYY-MM-DD");
String lastmodi = format.format(new Date(lastmod));
File newfile = new File(
"C:\\Users\\<User Name>\\desktop\\test\\"
+ lastmodi + ".csv");
// If rename successful, then print success with file
// location
if (myFile.renameTo(newfile)) {
System.out
.println("File Name Change Successful, New File Created:"
+ newfile.getPath());
} else {
System.out.println("File Name Change Failed");
}
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.