Search code examples
javafilefilewriterbufferedwriterreplaceall

Java BufferedWriter exporting file/directory listing .replaceAll alternative?


Exporting a given directory and file list to a file using BufferedWriter on Java8 (Eclipse IDE). This is working fine.

Some files have special characters like "[", "]" or extensions such as ".zip" that I wish to strip out when saving my file. Tried .replaceALL but getting stuck with how to make this work. Any suggestions please?

public static void getDirectoryList() throws IOException
{
String path = "C:\\Users\\";
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
File file = new File("DirectoryList.txt");
if (!file.exists()) {
    file.createNewFile();
}
FileWriter fw = new FileWriter(file.getName());
BufferedWriter bw = new BufferedWriter(fw);
for (File f : listOfFiles) {

        // .replaceALL wants to be cast. Is there an alternative to 
        // .replaceAll when listing out a file listing to file.
        // Or, am I doing something silly....
        f = f.replaceAll(".zip", "");
        bw.write(f.getName());
        bw.newLine();
    }
bw.close();
}

Example of Current text file output:

[name1].doc <-trying to remove "[" and "]" when saving name to file.

filename.zip <-trying to remove ".zip" when saving name to file.

directoryname1

directoryname2

(Original file and directory names remain, only the results save to the file are being changed.)

Required text file output

name1.doc

filename

directoryname1

directoryname2


Solution

  • replaceAll isn't a method of File, it's a method of String.

    for(File f : listOfFiles) {
         String fileName = f.getName();
         fileName = fileName.replaceAll("\\.zip", "");
         fileName = fileName.replaceAll("\\[", "");
         fileName = fileName.replaceAll("]", "");
    
         bw.write(fileName);
         bw.newLine();
    }
    

    Also notice that when I use replaceAll to remove '.zip' from the filename the . must be escaped. That's because the first parameter of replaceAll is a regex and dot . is a special character. The same for [.

    There is a more compact way to do the same thing with a single regex

    for(File f : new File("").listFiles()) {
         String fileName = f.getName();
         fileName = fileName.replaceAll("\\.zip|\\[|]", "");
    
         bw.write(fileName);
         bw.newLine();
    }