【问题标题】:reading a file using File separator in java在java中使用文件分隔符读取文件
【发布时间】:2018-06-13 16:35:17
【问题描述】:

我正在尝试在 java 中读取文件的内容,但我需要使其独立于平台。所以,我做到了

FileInputStream fis = new FileInputStream(new File(File.separator + "com" + File.separator + "test.txt"));
BufferedReader  br = new BufferedReader(new InputStreamReader(fis));

我正在尝试在 Eclipse 中运行它。 但我收到FileNotFoundExcption。现在我的test.txt 和我的源文件在同一个位置。请任何人都可以指导我完成它。 eclipse到底在哪里寻找这个文件? 提前谢谢..

【问题讨论】:

  • 你确定绝对路径是 /com/test.txt 吗?
  • eclipse构建项目时,所有非源文件也复制到bin文件夹中。默认情况下,您的应用程序在项目文件夹中运行。所以路径将是 bin//test.txt
  • 是的,这就是我想要的绝对路径。但我不知道日食会在哪里寻找它?我的意思是它指向我的 eclipse workspace/com/test.txt 还是 c:/com/test.txt??
  • 您可以通过打印文件对象的绝对路径让 Java 告诉您正在查看的位置。

标签: java filenotfoundexception


【解决方案1】:
File a = new File(File.separator + "com" + File.separator + "test.txt");
System.out.println(a.getAbsolutePath());

可能会输出一些你没有预料到的东西。

如果您发布返回的内容,我可以告诉您您的问题是什么。

它可能使用项目目录,您可以使用以下命令输出:

how to Locate the path of the Current project in Java, Eclipse?


解决方案:

如果windows上的路径是:

C:\com\test.txt

但在 linux 上你想要:

/com/test.txt

你想使用:

new File(System.getenv("SystemDrive") + File.separator + "com" + File.separator + "test.txt")

因为这将如上所述。

【讨论】:

  • 超级......这就是我想要的。不知道为什么我没想到:) 非常感谢你拯救了我的一天....
  • File a = new File(File.separator + "com" + File.separator + "test.txt"); 已经是绝对路径,所以打印a.getAbsolutePath() 会给出“/com/test.txt”。
  • @DodgyCodeException no... 它不会。它可能会打印 <some_random_path_to_working_dir>/com/test.txt b/c 我猜 OP 正在 Windows 而不是 Linux 上进行测试。在 Windows 上,/ 指示当前工作目录,而不是 root。
  • System.getenv("SystemDrive"); 将为您提供 Windows 系统的默认驱动器(例如 C:),并在 Linux 机器上抛出异常/不返回任何内容(我忘记了,请参阅 API 文档)。您可以使用它在 Windows 上创建一个也适用于 Linux 的 absolutePath,因为如果它没有检测到驱动器前缀,它将自动删除。在 Windows 上 new File("/").getAbsolutePath() 将打印您的项目目录(如果在 eclipse 中)
  • 不,在 Windows 上“/”表示当前驱动器的 根目录。所以如果你从D:\one\two\three 运行,那么new File("/").getAbsolutePath() 将返回D:\。
【解决方案2】:

绝对版本,可能不是你想要的:

BufferedReader br = new BufferedReader( new FileReader( "/com/test.txt" ));

相对版本:

BufferedReader br = new BufferedReader( new FileReader( "com/test.txt" ));

由操作系统专门化的 Java File 对象将这个通用路径转换为依赖于平台的形式。

路径是相对于执行路径的,Eclipse有一个小作用:你可以在Run/Debug对话框中给出执行的根路径。

【讨论】:

  • 为什么在根目录下却有/com/
  • 我不知道,这不是问题所在。我认为这是一个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-30
  • 2012-12-23
  • 2023-03-31
  • 1970-01-01
  • 2020-05-15
  • 2015-07-07
  • 2019-12-07
相关资源
最近更新 更多