这应该是简单的,但我不能得到它 - “写一个程序,搜索在指定目录下的特定文件名” 我发现一个硬编码的文件名和目录的几个例子,但我需要两个目录和文件名须为用户输入。
public static void main(String[] args) {
String fileName = args[0]; // For the filename declaration
String directory;
boolean found;
File dir = new File(directory);
File[] matchingFiles = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String fileName) {
return true;
}
});
}
Answer 1:
你可以尝试这样的事:
import java.io.*;
import java.util.*;
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("Enter the file to be searched.. " );
String name = scan.next();
System.out.println("Enter the directory where to search ");
String directory = scan.next();
ff.findFile(name,new File(directory));
}
}
下面是输出:
J:\Java\misc\load>java FindFile
Enter the file to be searched..
FindFile.java
Enter the directory where to search
j:\java\
FindFile.java Found in->j:\java\misc\load
Answer 2:
这看起来像一个家庭作业的问题,所以我只给你几个指针:
尽量提供良好的鲜明的变量名。 在这里,您使用的“文件名”第一的目录,然后为文件。 这是混乱的,并不会帮助你解决问题。 使用不同的事物有不同的名称。
你不使用扫描仪的任何东西,它没有必要在这里,摆脱它。
此外,接受方法应该返回一个布尔值。 现在,你正试图返回一个字符串。 布尔意味着它要么返回true或false。 例如return a > 0;
可以根据a的值返回true或false。 但return fileName;
只返回文件名,这是一个字符串的值。
Answer 3:
如果要使用动态文件名过滤器可以实现的FilenameFilter,并通过在构造函数中的动态域名。
当然,这意味着taht必须实例每次类(开销),但它的工作原理
例:
public class DynamicFileNameFilter implements FilenameFilter {
private String comparingname;
public DynamicFileNameFilter(String comparingName){
this.comparingname = comparingName;
}
@Override
public boolean accept(File dir, String name) {
File file = new File(name);
if (name.equals(comparingname) && !file.isDirectory())
return false;
else
return true;
}
}
然后你使用,你需要:
FilenameFilter fileNameFilter = new DynamicFileNameFilter("thedynamicNameorpatternYouAreSearchinfor");
File[] matchingFiles = dir.listFiles(fileNameFilter);
Answer 4:
随着**的Java 8 *有使用流和lambda表达式的选择:
public static void recursiveFind(Path path, Consumer<Path> c) {
try (DirectoryStream<Path> newDirectoryStream = Files.newDirectoryStream(path)) {
StreamSupport.stream(newDirectoryStream.spliterator(), false)
.peek(p -> {
c.accept(p);
if (p.toFile()
.isDirectory()) {
recursiveFind(p, c);
}
})
.collect(Collectors.toList());
} catch (IOException e) {
e.printStackTrace();
}
}
因此,这将递归打印的所有文件:
recursiveFind(Paths.get("."), System.out::println);
这将搜索文件:
recursiveFind(Paths.get("."), p -> {
if (p.toFile().getName().toString().equals("src")) {
System.out.println(p);
}
});
Answer 5:
使用Java 8+功能,我们可以写几行代码:
protected static Collection<Path> find(String fileName, String searchDirectory) throws IOException {
try (Stream<Path> files = Files.walk(Paths.get(searchDirectory))) {
return files
.filter(f -> f.getFileName().toString().equals(fileName))
.collect(Collectors.toList());
}
}
Files.walk
返回一个Stream<Path>
其中“行走在根的文件树”给定searchDirectory
。 只选择一个过滤器上所施加的所需的文件Stream
files
。 它比较一个文件名Path
与给定的fileName
。
请注意, 文件的Files.walk
要求
此方法必须一试,与资源性陈述或者类似的控制结构内使用,以确保数据流的开放目录及时关闭流的操作完成之后。
我使用的尝试资源语句 。
对于高级搜索的替代是使用PathMatcher
:
protected static Collection<Path> find(String searchDirectory, PathMatcher matcher) throws IOException {
try (Stream<Path> files = Files.walk(Paths.get(searchDirectory))) {
return files
.filter(matcher::matches)
.collect(Collectors.toList());
}
}
一个例子如何使用它来找到一个特定的文件:
public static void main(String[] args) throws IOException {
String searchDirectory = args[0];
String fileName = args[1];
PathMatcher matcher = FileSystems.getDefault().getPathMatcher("regex:.*" + fileName);
Collection<Path> find = find(searchDirectory, matcher);
System.out.println(find);
}
更多关于它: 甲骨文查找文件教程
Answer 6:
我用不同的方法来搜索使用堆栈文件..记住,有可能是一个文件夹内的文件夹。 虽然它比Windows搜索不是更快(我没想到的是,虽然),但它肯定给出了正确的结果。 如你所愿,请修改代码。 此代码最初是为了提取特定文件扩展名的文件路径:)。 随意优化。
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* @author Deepankar Sinha
*/
public class GetList {
public List<String> stack;
static List<String> lnkFile;
static List<String> progName;
int index=-1;
public static void main(String args[]) throws IOException
{
//var-- progFile:Location of the file to be search.
String progFile="C:\\";
GetList obj=new GetList();
String temp=progFile;
int i;
while(!"&%@#".equals(temp))
{
File dir=new File(temp);
String[] directory=dir.list();
if(directory!=null){
for(String name: directory)
{
if(new File(temp+name).isDirectory())
obj.push(temp+name+"\\");
else
if(new File(temp+name).isFile())
{
try{
//".exe can be replaced with file name to be searched. Just exclude name.substring()... you know what to do.:)
if(".exe".equals(name.substring(name.lastIndexOf('.'), name.length())))
{
//obj.addFile(temp+name,name);
System.out.println(temp+name);
}
}catch(StringIndexOutOfBoundsException e)
{
//debug purpose
System.out.println("ERROR******"+temp+name);
}
}
}}
temp=obj.pop();
}
obj.display();
// for(int i=0;i<directory.length;i++)
// System.out.println(directory[i]);
}
public GetList() {
this.stack = new ArrayList<>();
this.lnkFile=new ArrayList<>();
this.progName=new ArrayList<>();
}
public void push(String dir)
{
index++;
//System.out.println("PUSH : "+dir+" "+index);
this.stack.add(index,dir);
}
public String pop()
{
String dir="";
if(index==-1)
return "&%@#";
else
{
dir=this.stack.get(index);
//System.out.println("POP : "+dir+" "+index);
index--;
}
return dir;
}
public void addFile(String name,String name2)
{
lnkFile.add(name);
progName.add(name2);
}
public void display()
{
GetList.lnkFile.stream().forEach((lnkFile1) -> {
System.out.println(lnkFile1);
});
}
}
Answer 7:
下面的代码有助于搜索文件的目录,并打开其位置
import java.io.*;
import java.util.*;
import java.awt.Desktop;
public class Filesearch2 {
public static void main(String[] args)throws IOException {
Filesearch2 fs = new Filesearch2();
Scanner scan = new Scanner(System.in);
System.out.println("Enter the file to be searched.. " );
String name = scan.next();
System.out.println("Enter the directory where to search ");
String directory = scan.next();
fs.findFile(name,new File(directory));
}
public void findFile(String name,File file1)throws IOException
{
File[] list = file1.listFiles();
if(list!=null)
{
for(File file2 : list)
{
if (file2.isDirectory())
{
findFile(name,file2);
}
else if (name.equalsIgnoreCase(file2.getName()))
{
System.out.println("Found");
System.out.println("File found at : "+file2.getParentFile());
System.out.println("Path diectory: "+file2.getAbsolutePath());
String p1 = ""+file2.getParentFile();
File f2 = new File(p1);
Desktop.getDesktop().open(f2);
}
}
}
}
}
Answer 8:
该方法将递归搜索直通从根开始每个目录,直到文件名被发现,或者所有剩余的结果回来空。
public static String searchDirForFile(String dir, String fileName) {
File[] files = new File(dir).listFiles();
for(File f:files) {
if(f.isDirectory()) {
String loc = searchDirForFile(f.getPath(), fileName);
if(loc != null)
return loc;
}
if(f.getName().equals(fileName))
return f.getPath();
}
return null;
}
Answer 9:
public class searchingFile
{
static String path;//defining(not initializing) these variables outside main
static String filename;//so that recursive function can access them
static int counter=0;//adding static so that can be accessed by static methods
public static void main(String[] args) //main methods begins
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the path : ");
path=sc.nextLine(); //storing path in path variable
System.out.println("Enter file name : ");
filename=sc.nextLine(); //storing filename in filename variable
searchfile(path);//calling our recursive function and passing path as argument
System.out.println("Number of locations file found at : "+counter);//Printing occurences
}
public static String searchfile(String path)//declaring recursive function having return
//type and argument both strings
{
File file=new File(path);//denoting the path
File[] filelist=file.listFiles();//storing all the files and directories in array
for (int i = 0; i < filelist.length; i++) //for loop for accessing all resources
{
if(filelist[i].getName().equals(filename))//if loop is true if resource name=filename
{
System.out.println("File is present at : "+filelist[i].getAbsolutePath());
//if loop is true,this will print it's location
counter++;//counter increments if file found
}
if(filelist[i].isDirectory())// if resource is a directory,we want to inside that folder
{
path=filelist[i].getAbsolutePath();//this is the path of the subfolder
searchfile(path);//this path is again passed into the searchfile function
//and this countinues untill we reach a file which has
//no sub directories
}
}
return path;// returning path variable as it is the return type and also
// because function needs path as argument.
}
}
文章来源: Java - Search for files in a directory