java FileInputStream 使用包路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10697255/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
FileInputStream using package path
提问by Krishna
I am trying to read a file like :
我正在尝试读取如下文件:
FileInputStream fileInputStream = new FileInputStream("/com/test/Test.xml");
I am always getting the file not found exception. How can i make it work? Will the inputstream takes the relative path or not?
我总是收到找不到文件的异常。我怎样才能让它工作?输入流是否会采用相对路径?
回答by AlexR
Yes, this can take relative path.
是的,这可以采取相对路径。
Why your expression does not work? Very simple: your path /com/test/Test.xml
is absolute because it starts with /
, so you are actually looking for file located in /com/test/
directory starting from root.
为什么你的表达不起作用?非常简单:您的路径/com/test/Test.xml
是绝对路径,因为它以 开头/
,因此您实际上是在/com/test/
从根目录开始查找位于目录中的文件。
How to solve the problem?
如何解决问题?
I believe that you are trying to find file located under your project. So, you can use relative path like ./com/test/Test.xml
or com/test/Test.xml
. This will probably help. Probably because I do not know what is your current working directory and your file structure. Your current directory is where you are located when running java
. If you are running from IDE typically the working directory is your project directory.
我相信您正在尝试查找位于您的项目下的文件。因此,您可以使用相对路径,例如./com/test/Test.xml
或com/test/Test.xml
。这可能会有所帮助。可能是因为我不知道您当前的工作目录和文件结构是什么。您的当前目录是您在运行时所在的位置java
。如果您从 IDE 运行,通常工作目录是您的项目目录。
In this case I believe that path ./com/test/Test.xml
is invalid because file Test.xml
is not located directly under project root but somewhere under ./src/resources/com/test
or so.
在这种情况下,我认为路径./com/test/Test.xml
无效,因为文件Test.xml
不是直接位于项目根目录下,而是位于以下某处./src/resources/com/test
。
In this case probably you do not want to read the file as a file but as a resource (located into your classpath). In this case use
在这种情况下,您可能不想将文件作为文件读取,而是作为资源(位于类路径中)读取。在这种情况下使用
getClass().getResourceAsStream("/com/test/Test.xml")
getClass().getResourceAsStream("/com/test/Test.xml")
回答by mprabhat
Try using
尝试使用
class.getResourceAsStream(path). In that case, path will have to be relative to the folder containing the class invoking this statement.
class.getResourceAsStream(path)。在这种情况下,路径必须相对于包含调用此语句的类的文件夹。
InputStream in = getClass().getResourceAsStream("/com/test/Test.xml");
回答by Kumar Vivek Mitra
Try this,
试试这个,
String str = "Test.xml";
File file = new File(str);
String absolutePathOfFirstFile = file.getAbsolutePath();
FileInputStream fileInputStream = new FileInputStream(absolutePathOfFirstFile);
回答by user845279
Your path must be incorrect. You can check the current directory by using System.getProperty("user.dir");
or printing the path of new File(".")
您的路径一定不正确。您可以通过使用System.getProperty("user.dir");
或打印路径来检查当前目录new File(".")