日安!
我用Java编写了这个方法,它必须在文件夹中搜索文件并对它们执行一些操作。
所以问题是,当我试图检查我拥有什么(文件或dir)时,我在这两种情况下都没有收到任何信息!但在我看来,路径看起来是正确的。
我怎样才能解决这个问题?
以下是代码:
public void searchInDir(){
File inputFile = new File( this.fileName );
String[] namesOfFilesDir = inputFile.list();
for ( int i = 0; i < namesOfFilesDir.length; i++ )
{
String normalPath = this.getNormalPath(inputFile.getCanonicalPath()); //C:\User -> C:\\User
// Two separators for correcting path to file
String pathToCurrentFile = normalPath + File.separator + File.separator + namesOfFilesDir[i];
File f = new File( pathToCurrentFile, namesOfFilesDir[i] );
System.out.printf("FileName=%s, Path=[%s]\n", namesOfFilesDir[i], pathToCurrentFile);
System.out.println(f.isDirectory());//False
System.out.println(f.isFile());//False too
//Some other code
}
}例如,this.fileName包含指向文件夹的路径(此文件夹由一个文件夹和两个文件组成)。
我有下一个:
FileName=Readme.txt, Path=[C:\\workspace\\Grep\\t\\Readme.txt]
false
false
FileName=t2, Path=[C:\\workspace\\Grep\\t\\t2]
false
false
FileName=test.txt, Path=[C:\\workspace\\Grep\\t\\test.txt]
false
false好的。节目上这么说。
让我们打印下一段代码作为示例。
File f = new File("C:\\workspace\\Grep\\t\\Readme.txt");
System.out.println(f.isFile());程序将打印“真”。
发布于 2011-01-29 19:33:52
这部分毫无意义:
String pathToCurrentFile = normalPath + File.separator + File.separator + namesOfFilesDir[i];
File f = new File( pathToCurrentFile, namesOfFilesDir[i] );即使暂时忘记了双分隔符,首先通过添加namesOfFilesDir[i]来构造文件名,然后使用基本再次添加namesOfFilesDir[i]的双参数构造函数构造File()对象也是没有意义的。尝试打印f.getAbsolutePath(),您就会明白我的意思了。应该是这样的:
File f = new File( normalPath, namesOfFilesDir[i] );发布于 2011-01-29 19:03:40
可能这个文件不存在,所以它既不是文件也不是目录。也尝试打印f.exists()的输出。
您注意到路径中的重复文件分隔符了吗?
发布于 2011-01-29 19:09:00
我想也许你的路不对。只有当文件/目录实际存在时,isFile()和isDirectory()才返回true。你试过在文件上打电话给exists()吗?此外,我怀疑您的getNormalPath()方法正在做什么-我认为它可能是损坏文件名。
https://stackoverflow.com/questions/4838788
复制相似问题