Java的。文件和文件夹。无法定义类型

时间:2011-01-29 18:55:28

标签: java file directory

美好的一天!

我在Java中编写了这个方法,它必须搜索文件夹中的文件并对它们进行一些操作。

所以问题是,当我尝试检查我拥有的内容(文件或目录)时,我在两种情况下都没有收到任何内容!但是我可以看到路径看起来正确。

如何解决此问题?

以下是代码:

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包含文件夹的路径(此文件夹包含一个文件夹和2个文件)。

我接下来:

    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());

程序将打印“True”。

4 个答案:

答案 0 :(得分:2)

这部分毫无意义:

    String pathToCurrentFile = normalPath + File.separator + File.separator + namesOfFilesDir[i];
    File f = new File( pathToCurrentFile, namesOfFilesDir[i] );

即使我们暂时忘记了双分隔符,首先通过添加namesOfFilesDir[i]来构造文件名是没有意义的,然后使用双参数构造函数构造一个File()对象,它基本上添加了再次namesOfFilesDir[i]。尝试打印f.getAbsolutePath(),你会明白我的意思。它可能应该是这样的:

    File f = new File( normalPath, namesOfFilesDir[i] );

答案 1 :(得分:1)

可能该文件不存在,因此它既不是文件也不是目录。尝试打印f.exists()的输出。

您是否注意到路径中的重复文件分隔符?

答案 2 :(得分:1)

我想也许你的道路不正确。如果文件/目录实际存在,isFile()isDirectory()都只返回true。你试过在文件上调用exists()吗?另外,我怀疑你的getNormalPath()方法正在做什么 - 我认为它可能会破坏文件名。

答案 3 :(得分:1)

第一个System.out.println是误导性的!
输出f的路径会更好。

无论如何,根据输出:

  

FileName = Readme.txt,Path = [C:\ workspace \ Grep \ t \ Readme.txt]

f将为C:\workspace\Grep\t\Readme.txt\Readme.txt 也就是说,namesOfFilesDir[i]被追加两次!

直接使用File实例更容易/更好:

    File inputFile = new File(this.fileName); 
    File[] files = inputFile.listFiles();
    for (File f : files) {
        System.out.printf("FileName=%s, Parent=[%s]\n", f.getName(), f.getParent());
        System.out.println(f.isDirectory());
        System.out.println(f.isFile());         
        //Some other code
    }