2015-06-21 107 views
0

我似乎无法理解如何传递文件夹来加载类路径中的文件。它适用于.class文件所在文件夹中的文本文件,或者如果我使用files/test.txt而不是test.txt。我究竟做错了什么?访问类路径中给出的文件夹中的文件

代码:

import java.io.*; 

public class T { 
    public static void main(String[] args) { 
     String line; 
     File f = new File("test.txt"); 
     BufferedReader reader = null; 
     try { 
      reader = new BufferedReader(new FileReader(f)); 
      while ((line = reader.readLine()) != null) { 
       System.out.println(line); 
      } 
     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      try { 
       if (reader != null) { 
        reader.close(); 
       } 
      } catch (IOException e) { 
      } 
     } 
    } 
} 

文件夹和文件:

stuff/T.java 
stuff/T.class 

某处有一个文件与我想在classpath给予test.txt文件夹中。

我使用命令java -cp .../files T在windows命令行中的东西文件夹中运行测试。

+0

text.txt的相对路径是'files/test.txt',如果您希望它只是'test.txt'将它与类文件放在一起。如果有一些类或库,将文件添加到类路径将会很有用。 –

+0

如果我有一个jar文件,我想添加一些新的文本文件用于各种事情?我如何将它们交给罐子使用? – Sunspawn

+0

你将再次必须使用相对路径[http://stackoverflow.com/questions/2393194/how-to-access-resources-in-jar-file –

回答

0
String dirPath = "/Users/you/folder/"; 
String fileName = "test.txt"; 

File directory = new File(dirPath); 
File file = new File(directory, fileName); 

// Read file now 

你可以在任何文件对象上使用.exists()来检查它是否存在。

0

检查File是否是一个目录,然后根据需要遍历目录的内容。

public class T { 

    public static void main(String[] args) { 
     File f = new File("stuff"); 

     if(f.isDirectory()){ 
      for(File file:f.listFiles()){ 
       printFileName(file); 
      } 
     }else{ 
      printFileName(f); 
     } 
    } 

    private static void printFileName(File f) { 
     String line; 
     BufferedReader reader = null; 
     try { 
      reader = new BufferedReader(new FileReader(f)); 
      while ((line = reader.readLine()) != null) { 
       System.out.println(line); 
      } 
     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      try { 
       if (reader != null) { 
        reader.close(); 
       } 
      } catch (IOException e) { 
      } 
     } 
    } 
} 

如果您不确定哪个目录代码寻找File的输出当前目录。

File file = new File("."); 
System.out.println(file.getAbsolutePath()); 
相关问题