Java字符串替换方法不';t更换我的'\';与'/';文件查找器类

Java字符串替换方法不';t更换我的'\';与'/';文件查找器类,java,file,replace,Java,File,Replace,我的输出有\ 我的预期产出是: temp/F1.java temp/F2.java temp/subtemp/F3.java 怎么了 public class FileFinder { public static void main(String[] args) throws IOException { File dir1 = new File("temp"); dir1.mkdir() ; File f1 = new File("te

我的输出有\

我的预期产出是:

temp/F1.java
temp/F2.java
temp/subtemp/F3.java
怎么了

public class FileFinder
{
    public static void main(String[] args) throws IOException
    {
       File dir1 = new File("temp");
       dir1.mkdir() ;
       File f1 = new File("temp/F1.java") ;
       f1.createNewFile() ;
       File f2 = new File("temp/F2.java") ;
       f2.createNewFile() ;
       File dir2 = new File("temp/subtemp") ;
       dir2.mkdir() ;
       File f3 = new File("temp/subtemp/F3.java") ;
       f3.createNewFile() ;
       find(dir1, ".java");
    }

    /**
       Prints all files whose names end in a given extension.
       @param aFile a file or directory
       @param extension a file extension (such as ".java")
    */
    public static void find(File aFile, String extension)
    {            
        //-----------Start below here. To do: approximate lines of code = 10
        // 1. if aFile isDirectory 
        if (aFile.isDirectory()) {
            //2. use listFiles() to get an array of children files 
            File[] children = aFile.listFiles();
            //3. use sort method of Arrays to sort the children 
            Arrays.sort(children);
            //4. for each file in the sorted children 
            for (File child : children) {
                //5. recurse  
                find(child, extension);
            }
        }//
        else {//
            //6. otherwise the file is not a directory, so 
            //use toString() to get the file name 
            String fileName = aFile.toString();
            //7. use replace() to change '\' to '/' 
            fileName.replace('\'' , '/');
            //8. if the file name endsWith the extension 
            if (fileName.endsWith(extension)) {
                //9. then print it.     
                System.out.println(fileName);
            }
        }
        //-----------------End here. Please do not remove this comment. Reminder: no changes outside the todo regions.
    }
}
此代码

fileName.replace('\'' , '/');
正在将
'
更改为
/
并使用使用regexp的replaceAll

你想要的是

fileName.replaceAll("\\" , "/");
但是事实上,为什么还要为这段代码而烦恼呢,您甚至都没有保存替换的结果。为此你需要

fileName = fileName.replaceAll("\\" , "/");

你需要逃离刀口。目前,您正在转义单个报价

更改:

fileName.replace('\'' , '/');
致:

replace()不会更改该值,您必须再次保存它,这是我在上面所做的。

如果您查看Javadocs,char),您将看到replace不适用于正则表达式。使用replaceAll。
fileName = fileName.replace('\\' , '/');