我有一组文件,如" f-1.txt" ," f-2.txt",.....," f-30.txt"," g-1.txt" ," g-2.txt",.....," g-23.txt"," h-1.txt" ," h-2.txt",.....," h-35.txt" ..等等在一个文件夹中。我想为每个文件夹添加一些内容并将它们重命名为" f-1new.txt" ," g-2new.txt"。我怎样才能在java中引用它们,最好是使用通配符并适当地重命名它们?
对于一个特殊文件,我使用BufferedReader来读取它的内容,然后使用Printwriter将修改后的内容写入一个新的文件名。但是,如果名称变化太大(如果有的话),我怎样才能(迭代地)读取所有文件中的内容如上所述?
我已经改回this但它没有帮助我如何获取数组中每个文件的文件名(帖子中的第一个答案)..
答案 0 :(得分:1)
尝试以下方法:
//This method will return files with matching pattern in the specified directory
public File[] getMatchingFiles(String yourDirectoryWithFiles){
File directoryWithFiles= new File(yourDirectoryWithFiles);
return directoryWithFiles.listFiles(new FilenameFilter() {
public boolean accept(File dir, String filename)
{ //Make this dynamic with passing the pattern as an argument
return filename.endsWith("f.*txt");
}
} );
}
//Iterate over the files and rename them
public void iterateFiles(String yourDirectoryWithFiles){
File[] fileList=getMatchingFiles(yourDirectoryWithFiles);
for(File oldFile:fileList){
boolean success=createNewFile(oldFile);
//Case 1 :Deleting the old file if file creation was successful
if(success)
oldFile.delete();
//If using Case 2: return the newFileObject and call: oldFile.renameTo(newFile);
}
}
public boolean createNewFile(File oldFile){
//Case 1: create a new file object here and perform your name changing operations
//Case 2: If you don't want to create another file , write to the existing file
//but you would still need to create an file object to perform rename operation
}
答案 1 :(得分:0)
这是一个解决方案。
public class Main {
public static void main(String[] args) throws FileNotFoundException, IOException {
String PATH_2_FOLDER = "path_2_folder";
//listing all files in the desired folder
File myDirectory = new File(PATH_2_FOLDER);
File[] allFiles = myDirectory.listFiles();
System.out.println(allFiles.length);
for (int l = 0; l < allFiles.length; l++) {
if (allFiles[l].getName().endsWith(".txt")) {
//read the input file
String thisPathIn = PATH_2_FOLDER+allFiles[l].getName();
BufferedReader thisBR = new BufferedReader(new FileReader(thisPathIn));
//create the output file
String newName = allFiles[l].getName().replace(".txt", "").concat(".new.txt");
String thisPathOut = PATH_2_FOLDER+newName;
BufferedWriter thisBW = new BufferedWriter(new FileWriter(thisPathOut));
//read the contents of the inputfile
String s = "";
while((s = thisBR.readLine()) != null){
//process the content
//...
//create new content
thisBW.write("new_content\n");
}
thisBW.flush();
thisBW.close();
}
}
}
}