如果不添加扩展名,则无法获取文件的大小(使用JFileDialog)

时间:2011-11-19 01:16:02

标签: java

这是我到目前为止所拥有的。当我在JFileDialog中输入文件名而没有它的扩展名时,我找到了文件,但是我无法获得大小....扩展名我得到了大小...但是我希望得到它没有它的扩展名

public class DirScanner {

    public static void main(String[] argv) throws IOException {

        FileDialog fd = new FileDialog(new Frame());
        fd.setVisible(true);//make the jfilechooer visible
        if (fd.getFile() != null) {

            File f = new File(fd.getDirectory(), fd.getFile());//svae directory path and name of file
            String p = null;
            File fi = new File(fd.getDirectory());//store directory

            String[] d = fi.list();//store all file in directory
            for (int i = 0; i < d.length; i++) {
                if (d[i] != null) {

                    //checks if wat the user type in the Jfieldoalog matches wat is in teh directory
                    if (d[i].matches(fd.getFile()) || d[i].startsWith(fd.getFile())) {

                        //gets the extension of teh file
                        p = d[i];
                        int dot = p.lastIndexOf(".");
                        String word = p.substring(0, dot);
                        String w = p.toUpperCase().substring(dot + 1);


                        System.out.println("\nFile Found\n");//output that file is found

                        //Display name of file with and without extension
                        System.out.println("Name of File: " + d[i]+  "\n"+  "File Name Without Extension: " + word + "\n" + "File type: " + w);
                    }
                }
            }
            //output size of fiel
            System.out.printf("size: " + f.length());
        }
    }
}

2 个答案:

答案 0 :(得分:0)

尝试在扫描期间构建新的File实例:

File file = new File(fd.getDirectory(), p);
System.out.println("size: " + file.length());

答案 1 :(得分:0)

尝试了解File is in Java以及您从方法.list()获得的内容。

当您打印“找到文件”时,您实际上只找到了与您在FileDialog中输入的内容相匹配的文件的全名。您需要use that name to find the file size