Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FileInputStream using package path

Tags:

java

file-io

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?

like image 660
Krishna Avatar asked Dec 21 '22 21:12

Krishna


1 Answers

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.

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.

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.

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")

like image 80
AlexR Avatar answered Jan 04 '23 14:01

AlexR