Java 在递归方法调用之间保留值
在下面的代码段中,如何保留找到的(path)值并将其返回给调用该方法的类Java 在递归方法调用之间保留值,java,Java,在下面的代码段中,如何保留找到的(path)值并将其返回给调用该方法的类 public void searchFile(Path searchFrom, String match) throws IOException { try(DirectoryStream<Path> SearchResult = Files.newDirectoryStream(searchFrom)) { for(Path check : SearchResult) {
public void searchFile(Path searchFrom, String match) throws IOException {
try(DirectoryStream<Path> SearchResult = Files.newDirectoryStream(searchFrom)) {
for(Path check : SearchResult) {
if(!Files.isDirectory(check) && check.toString().contains(match)) {
System.out.println(check.toString());
} else if(Files.isDirectory(check)) {
searchFile(check, match);
}
}
}
}
public void searchFile(路径searchFrom,字符串匹配)引发IOException{
try(DirectoryStream SearchResult=Files.newDirectoryStream(searchFrom)){
for(路径检查:SearchResult){
如果(!Files.isDirectory(check)&&check.toString()包含(匹配)){
System.out.println(check.toString());
}else if(Files.isDirectory(检查)){
搜索文件(检查、匹配);
}
}
}
}
目标是能够在目录树中递归地查找(文件)路径,并将其返回给调用该方法的类。找到时返回路径:
public Path searchFile(Path searchFrom, String match) throws IOException {
try(DirectoryStream<Path> SearchResult = Files.newDirectoryStream(searchFrom)) {
for(Path check : SearchResult) {
if(!Files.isDirectory(check) && check.toString().contains(match)) {
return check;
} else if(Files.isDirectory(check)) {
Path found=searchFile(check, match);
if (found!=null){
return found;
}
}
}
}
return null; // not found
}
public Path searchFile(Path searchFrom,String match)抛出IOException{
try(DirectoryStream SearchResult=Files.newDirectoryStream(searchFrom)){
for(路径检查:SearchResult){
如果(!Files.isDirectory(check)&&check.toString()包含(匹配)){
退货检查;
}else if(Files.isDirectory(检查)){
找到的路径=搜索文件(检查,匹配);
如果(找到!=null){
发现退货;
}
}
}
}
返回null;//未找到
}
传递第三个参数并将其作为返回值,
假设您需要多个返回值
(而不仅仅是JP Moresmau回答中所示的第一个问题)
比如说
public class Blammy
{
private List<Path> kapow = new LinkedList<Path>();
public addPath(final Path newPath)
{
kapow.add(newPath);
}
public List<Path> getKapow()
{
return kapow;
}
}
public void searchFile(
final Path searchFrom,
final String match,
final Blammy blammy) ...
...
// Instead of System.out.println(check.toString()); do this:
blammy.addPath(check);
...
公共类
{
private List kapow=new LinkedList();
公共addPath(最终路径newPath)
{
kapow.add(newPath);
}
公共列表getKapow()
{
返回卡波;
}
}
公共无效搜索文件(
最终路径从,
最后一场弦乐比赛,
最后的责备我的责备。。。
...
//而不是System.out.println(check.toString());这样做:
bummy.addPath(检查);
...
是否需要在结果中找到一个或多个路径?