我需要对这个Java程序做两点补充。
当我尝试搜索文件时,我需要让它显示完整的路径。此时它只在我搜索xmen.txt时显示E:\books\comics\
。我试图让它显示E:\books\comics\xmen.txt
作为结果。
如果在搜索时没有名称相同的文件,我需要告诉我没有找到结果。
另外,我没有接受过Java培训,这个程序是关于"搜索可能性"的主题的文书作业。我试图通过在主题中添加面向对象的编程来使它变得很酷。
class FindFile
{
public void findFile(String name, File file)
{
File[] list = file.listFiles();
if(list!=null)
for (File fil : list)
{
if (fil.isDirectory())
{
findFile(name,fil);
}
else if (name.equalsIgnoreCase(fil.getName()))
{
System.out.println(fil.getParentFile());
}
}
}
public static void main(String[] args)
{
FindFile ff = new FindFile();
Scanner scan = new Scanner(System.in);
System.out.println("Write the file you are trying to find:" );
String name = scan.next();
System.out.println("Write the directory where you want to search for the file");
String directory = scan.next();
System.out.println("File was found in: ");
ff.findFile(name,new File(directory));
}
}
答案 0 :(得分:1)
这样的事情,这需要一些工作:
import java.io.*;
import java.util.*;
class FindFile
{
public String findFile(String name,File file) throws IOException
{
File[] list = file.listFiles();
if (list != null)
{
for (File fil : list)
{
if (fil.isDirectory())
{
return findFile(name,fil);
}
else if (name.equalsIgnoreCase(fil.getName()))
{
return fil.getCanonicalPath();
}
}
}
return null;
}
public static void main(String[] args) throws IOException
{
FindFile ff = new FindFile();
Scanner scan = new Scanner(System.in);
System.out.println("Write the file you are trying to find:" );
String name = scan.next();
System.out.println("Write the directory where you want to search for the file");
String directory = scan.next();
String foundFile = ff.findFile(name,new File(directory));
if (foundFile != null)
{
System.out.println("File was found in: " + foundFile);
}
else
{
System.out.println("File was not found");
}
}
}