这应该是简单的,但我无法理解 - “编写一个程序来搜索给定目录中的特定文件名。”我找到了一些硬编码文件名和目录的例子,但是我需要用户输入的目录和文件名。
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;
}
});
}
答案 0 :(得分:25)
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
答案 1 :(得分:1)
这看起来像是一个家庭作业问题,所以我只想给你一些指示:
尝试提供良好的独特变量名称。这里首先使用“fileName”作为目录,然后使用文件。这很令人困惑,也无法帮助您解决问题。对不同的事物使用不同的名称。
你没有使用Scanner做任何事情,这里不需要它,摆脱它。
此外,accept方法应返回一个布尔值。现在,您正在尝试返回String。 Boolean表示它应该返回true或false。例如,return a > 0;
可能返回true或false,具体取决于a的值。但return fileName;
只会返回fileName的值,即String。
答案 2 :(得分:1)
如果要使用动态文件名过滤器,可以实现FilenameFilter并将构造函数传递给动态名称。
当然这意味着你必须在每次课时(开销)实例化,但它有效
示例:
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);
答案 3 :(得分:1)
使用** Java 8 *,有一种使用stream和lambdas的替代方法:
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);
}
});
答案 4 :(得分:1)
使用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
中的documentation需要
必须在try-with-resources语句中使用此方法,或者 类似的控制结构,以确保流的打开目录 流的操作完成后,将立即关闭。
我正在使用try-resource-statement。
对于高级搜索,一种替代方法是使用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);
}
如何使用它查找特定文件的示例:
{{1}}
有关它的更多信息:Oracle Finding Files tutorial
答案 5 :(得分:0)
我使用了一种不同的方法来搜索使用堆栈的文件..请记住文件夹中可能有文件夹。虽然它不比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);
});
}
}
答案 6 :(得分:0)
以下代码有助于在目录中搜索文件并打开其位置
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);
}
}
}
}
}
答案 7 :(得分:0)
此方法将从根目录开始递归搜索每个目录,直到找到fileName或所有其余结果返回空值。
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;
}
答案 8 :(得分:0)
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.
}
}
答案 9 :(得分:-1)
我尝试了很多方法来找到我想要的文件类型,这是我完成后的结果。
uploadFile() {
this.loadingService.start();
this.service.uploadFile(data).subscribe(() => {
this.toastr.success('file uploaded successfully');
this.loadingService.complete();
})
}