我的输出有\。
我的预期输出是:
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.
}
}
答案 0 :(得分:1)
你需要逃避斜线。目前你正在逃避单一报价。
变化:
fileName.replace('\'' , '/');
要:
fileName = fileName.replace('\\' , '/');
replace()不会改变值,你必须再次保存它,这就是我上面所做的。
答案 1 :(得分:0)
此代码
fileName.replace('\'' , '/');
正在将'
更改为/
并使用使用regexp的replaceAll
你想要的是
fileName.replaceAll("\\" , "/");
但实际上 - 为什么要烦恼这个代码,你甚至都没有保存替换的结果。为此你需要
fileName = fileName.replaceAll("\\" , "/");