如何从Java项目中的相对path读取文件? java.io.File找不到指定的path
我有一个项目与2包:
- tkorg.idrs.core.searchengines
-  tkorg.idrs.core.searchengines
 在包(2)我有一个文本文件ListStopWords.txt ,在包(1)我有一个类FileLoadder 。 这里是FileLoader代码: 
 File file = new File("properties\\files\\ListStopWords.txt"); 
但是有这个错误:
 The system cannot find the path specified 
你能给一个解决scheme来解决它吗? 谢谢。
 如果它已经在类path中,那就从类path中获取它。 不要在java.io.File使用相对path。 它们依赖于Java代码内部完全不受控制的当前工作目录。 
 假设ListStopWords.txt与FileLoader类在同一个包中: 
 URL url = getClass().getResource("ListStopWords.txt"); File file = new File(url.getPath()); 
 或者,如果你只是一个InputStream的话: 
 InputStream input = getClass().getResourceAsStream("ListStopWords.txt"); 
 如果文件是 – 包名称提示 – 实际上是一个完整的属性文件 (包含key=value行),只有“错误的”扩展名,那么你可以立即将它提供给load()方法。 
 Properties properties = new Properties(); properties.load(getClass().getResourceAsStream("ListStopWords.txt")); 
 注意:当你试图从static上下文中访问它时,在上面的例子中使用FileLoader.class而不是getClass() 。 
如果我们想要指定文件的相对path,可以使用下面这一行。
 File file = new File("./properties/files/ListStopWords.txt"); 
相对path在java中使用。 运营商。
- 。 意味着与当前运行的上下文相同的文件夹
- ..表示当前正在运行的上下文的父文件夹。
所以问题是如何知道java当前正在寻找的path?
做一个小实验
  File directory = new File("./"); System.out.println(directory.getAbsolutePath()); 
观察输出,你将会知道java正在查找的当前目录。 从那里,只需使用./运算符来查找您的文件。
例如,如果输出是
G:\ JAVA8Ws \ MyProject的\内容。
并且您的文件存在于MyProject文件夹中
 File resourceFile = new File("../myFile.txt"); 
希望这可以帮助
  InputStream in = FileLoader.class.getResourceAsStream("<relative path from this class to the file to be read>"); try { BufferedReader reader=new BufferedReader(new InputStreamReader(in)); String line=null; while((line=reader.readLine())!=null){ System.out.println(line); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } 
 请尝试.\properties\files\ListStopWords.txt 
虽然BalusC提供的答案适用于这种情况,但是当文件path包含空格时会中断,因为在URL中,这些文件将被转换为%20,这不是有效的文件名。 如果使用URI而不是String来构造File对象,则可以正确处理空格:
 URL url = getClass().getResource("ListStopWords.txt"); File file = new File(url.toURI()); 
我想parsingsrc / main / js / Simulator.java中的“command.json”。 为此,我复制了src文件夹中的json文件,并给了这样的绝对path:
 Object obj = parser.parse(new FileReader("./src/command.json")); 
 如果您试图从静态方法或静态块中调用getClass() ,则可以执行以下操作。 
 你可以调用你正在加载的Properties对象的getClass() 。 
 public static Properties pathProperties = null; static { pathProperties = new Properties(); String pathPropertiesFile = "/file.xml; InputStream paths = pathProperties.getClass().getResourceAsStream(pathPropertiesFile); } 
如果文本文件没有被读取,请尝试使用更接近的绝对path(如果您希望可以使用完整的绝对path),如下所示:
 FileInputStream fin=new FileInputStream("\\Dash\\src\\RS\\Test.txt"); 
假定绝对path是:
 C:\\Folder1\\Folder2\\Dash\\src\\RS\\Test.txt