[英]Program throws NullPointerException when i try to search in drives?
I wrote a program to find file or directory. 我写了一个程序来查找文件或目录。
Its working properly when i am trying to Search file with in Directory 当我尝试在目录中搜索文件时,它正常工作
example 例
java FileSearch abc.txt f:\\xyz
But when i am try to search file from local drive than program throw Exception 但是当我尝试从本地驱动器搜索文件而不是程序抛出异常时
java FileSearch abc.txt f:\\
after Showing all the search result throws NullPointerException. 显示所有搜索结果后抛出NullPointerException。
code is : 代码是:
import java.io.*;
class FileSearch{
static String fd;
static boolean flg=true;
public static void main(String arr[]){
fd=arr[0];
String path=arr[1];
String dir[]=new File(path).list();
new FileSearch().finder(dir,path);
if(flg){System.out.print("File not found.");}
}
public void finder(String[] dir,String path){
for(int i=0;i<dir.length;i++){
if(dir[i].equals(fd)){
System.out.println(path+"\\"+fd);
flg=false;
}
if(new File(path,dir[i]).isDirectory())
finder(new File(path,dir[i]).list(),path+"\\"+dir[i]);
}
}
}
I want to know why this exception is thrown and how can i fix it. 我想知道为什么抛出这个异常以及如何解决它。
The documentation of
listFiles()
mentions that it will returnnull
if this abstract pathname does not denote a directory, or if an I/O error occurs.listFiles()
的文档提到如果此抽象路径名不表示目录,或者发生I / O错误,它将返回null
。 Additionally, you would need to check withfile.canRead()
whether the application can read the directory.此外,您需要检查
file.canRead()
是否应用程序可以读取目录。
IMHO 恕我直言
Always use it this way; 总是以这种方式使用它;
String[] files = file.list();
if (files!=null) {
for (String f : files) processFile(f);
}
Recommend this; 推荐这个;
File directory = new File(directoryName);
//get all the files from a directory
File[] fList = directory.listFiles();
if(fList != null){
for (File file : fList){
if (file.isFile()){
System.out.println(file.getName());
}
}
}
Do let me know if you have any questions. 如果您有任何疑问,请告诉我。
Another alternative is to using the FileVisitor interface introduced in JDK7 to perform the search. 另一种方法是使用JDK7中引入的FileVisitor接口来执行搜索。 The link at http://docs.oracle.com/javase/tutorial/essential/io/walk.html provides details on how to use the FileVisitor interface.
http://docs.oracle.com/javase/tutorial/essential/io/walk.html上的链接提供了有关如何使用FileVisitor界面的详细信息。
The following code block is a re implementation of the search that should be able to list files at a windows drive level in addition to normal directories. 以下代码块是搜索的重新实现,除了普通目录之外,还应该能够在Windows驱动器级别列出文件。 Note that the implementation uses Files.walkTree method that is provided as part of the NIO 2 File IO Operations.
请注意,该实现使用作为NIO 2文件IO操作的一部分提供的Files.walkTree方法。
public class FileSearch {
static String fd;
static boolean flg = true;
static class FileSearchVisitor extends SimpleFileVisitor<Path> {
private final Path pathToSearch;
boolean found;
FileSearchVisitor(Path pathToSearch) {
found = false;
this.pathToSearch = pathToSearch;
}
public boolean isFound() {
return found;
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
super.preVisitDirectory(dir, attrs);
if (pathToSearch.getFileName().equals(dir.getFileName())) {
System.out.println("Found " + pathToSearch);
found = true;
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
super.visitFile(file, attrs);
if (pathToSearch.getFileName().equals(file.getFileName())) {
System.out.println("Found " + pathToSearch);
found = true;
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) {
System.err.println("Visit failed for file at path : " + file);
exc.printStackTrace();
return FileVisitResult.CONTINUE;
}
}
public static void main(String arr[]) throws Exception {
fd = arr[0];
String path = arr[1];
final Path searchFile = Paths.get(fd);
Path filePath = Paths.get(path);
FileSearchVisitor visitor = new FileSearchVisitor(searchFile);
Files.walkFileTree(filePath, visitor);
if (!visitor.isFound()) {
System.out.print("File not found.");
}
}
}
This is how you fix it: 这是你如何解决它:
import java.io.*;
class FileSearch{
static String fd;
static boolean flg=true;
public static void main(String arr[]){
fd=arr[0];
String path=arr[1];
String dir[]=new File(path).list();
new FileSearch().finder(dir,path);
if(flg){System.out.print("File not found.");}
}
public void finder(String[] dir,String path){
if(dir == null){
return;
}
for(int i=0;i<dir.length;i++){
if(dir[i].equals(fd)){
System.out.println(path+"\\"+fd);
flg=false;
}
if(new File(path,dir[i]).isDirectory())
finder(new File(path,dir[i]).list(),path+"\\"+dir[i]);
}
}
}
Why? 为什么? String dir[]=new File(path).list();
String dir [] = new File(path).list(); on the directory you specified is null so when you call dir.length you will get null pointer exception
在您指定的目录上为null,因此当您调用dir.length时,您将获得空指针异常
another thing that will help you understand, System.out.print(new File(path).isDirectory()); 另一件可以帮助你理解的事情是System.out.print(new File(path).isDirectory()); if its false, then you will get null pointer exception.
如果它是假的,那么你将获得空指针异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.