gpt4 book ai didi

Java String 替换方法不会用 '\' File Finder 类替换我的 '/'

转载 作者:行者123 更新时间:2023-12-01 13:19:48 26 4
gpt4 key购买 nike

我的输出有\.

我的预期输出是:

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('\'' , '/');

致:

fileName = fileName.replace('\\' , '/');

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

关于Java String 替换方法不会用 '\' File Finder 类替换我的 '/',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22138460/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com