2011-11-19 75 views
-2

这是迄今为止我所拥有的。当我在JFileDialog中输入没有扩展名的文件名时,我找到了文件,但是我无法获得大小......扩展名的大小...但是我想得到它的扩展名无法添加文件的扩展名(使用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()); 
     } 
    } 
} 
+0

你的代码和问题没有多大意义。您正在自己扫描目录以查找该文件,但是当您找到该文件时,您无法从该文件获取该文件的长度,而是从JileChooser返回的文件中获取该文件。 – EJP

+0

我知道有什么不对,但我不知道如何解决它可以帮助你吗? –

+0

我刚刚做到了。再读一遍。 – EJP

回答

0

尝试的扫描过程中构造一个新的File实例:

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

谢谢你们.. @orien它确实工作!噢!你知道什么关于阅读文件头来获取文件类型(扩展名)在Java? –