FileInputStream using package path - java

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?

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

Try using
class.getResourceAsStream(path). In that case, path will have to be relative to the folder containing the class invoking this statement.
InputStream in = getClass().getResourceAsStream("/com/test/Test.xml");

Try this,
String str = "Test.xml";
File file = new File(str);
String absolutePathOfFirstFile = file.getAbsolutePath();
FileInputStream fileInputStream = new FileInputStream(absolutePathOfFirstFile);

Your path must be incorrect. You can check the current directory by using System.getProperty("user.dir"); or printing the path of new File(".")

Related

How to find the path of a file local eclipse project

I have created a .txt file in my Eclipse Java project, and I want to find out the path to it so I can use it for a Scanner. I do not want to find out the path on my local drive, as I will be planning to share the program to someone else, and they will have a different folder structure, rather a path that can be used on anybodies machine.
Here is the code:
this.file = new File("<insert path here>");
you can use :
= new File("Build Path"); (your .java file exist in your build path)
The build path is used for building your application. It contains all of your source files and all Java libraries that are required to compile the application.
In eclipse, the default behavior is for the Java system property user.dir to be set to the project directory. This is what dictates where the "root" of File operations is. So if you created a file test.txt in the root project directory, you should be able to access it with new File("test.txt").
However, as Andrew Thompson mentioned in his comment, the more correct method would be using embedded resources.
Try one of These:
1.
System.getProperty("user.dir");
2.
File currentDirFile = new File(".");
String helper = currentDirFile.getAbsolutePath();
String currentDir = helper.substring(0, helper.length() - currentDirFile.getCanonicalPath().length());//this line may need a try-catch
I have not tested it just found while googling

Cannot access text file in java project

I am trying to access a text file, output.txt which is inside a project folder. The image below shows the folder structure.
String file=".\\testFiles\\output.txt";
BufferedReader br=new BufferedReader(new FileReader(file));
When I try to access that file using the code above, I get the following exception.
java.io.FileNotFoundException: .\testFiles\output.txt (No such file or directory)
I have tried different file path formats but none have worked. I think the problem is with the file path format.
Thanks in advance.
If I remember correctly you can get a folder/file in the current directory like so:
File folder = new File("testFiles");
Then you can open the file by getting the absolutePath and creating a new file with it, like so:
File file = new File(folder.getAbsoluteFile() + File.separator + "output.txt");
I'm not sure but I think you can also do:
File file = new File("testFiles/output.txt");
I hope this helps :)
P.S. this is all untested so it might not work.
Judging by the fact that you have a webcontent folder i presume this is a web project, possibly packaged as a war? In this case what you will want to do is package the respective files along with the classes and access it with something like this:
Thread.currentThread().getContextClassLoader().getResourceAsStream("output.txt")
The code above will work if you add the testFiles folder as a source folder (this means it will get packaged with the classes and be available at runtime)
The good thing is that this way the path can stay relative, no need to go absolute
I believe that your problem is due to the fact that you rely on a relative path as your path starts with a dot which means that it will by relative to the user directory (value of the system property user.dir) so I believe that your user directory is not what you expect. What you could do to debug is simply this:
System.out.println(new File(file).getAbsolutePath());
Thanks to this approach you will be able to quickly know if the absolute path is correct.
You must declare your file as a new file:
File yourFile = new File("testFiles/output.txt");

jsp web application relative path

I want to open a file in Java Class in an AWS Java Web project via Eclipse.
I have my file in a folder called "res" in
I tried this
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream("res\\txtFile.txt"), "UTF-8"));
but not working!
I got
java.io.FileNotFoundException: res\txtFile.txt (The system
cannot find the path specified)
If the file is inside the weapp, you want ServletContext.getResourceAsStream or Class.getResourceAsStream. If it is somewhere else on the filesystem you should probably use an absolute path. A relative path like you used is resolved relative to the directory your appserver started from which might not be what you want.
I solved it !!
used this code to get the absolute path of project anywhere
String AbsolutePath = new File("").getAbsolutePath();
then add the relative path you need.

How to scan a file in a different directory in java?

How do you scan a file with java that isn't in the directory the java file is in?
For example: The java file is located at "C:\Files\JavaFiles\test.java" However, the file I want to scan is located at "C:\Data\DataPacket99\data.txt"
Note: I've already tried putting another java file in the "C:\Data" directory and using the test.java file as a class, but it doesn't work. It still tries to scan from the "C:\Files\JavaFiles" Directory.
By using an absolute path instead of a relative.
File file = new File("C:\\Data\\DataPacket99\\data.txt");
Then you can write code that accesses that file object, using a InputStream or similar.
You need to use absolute paths in java.io stuff. Thus not new File("data.txt"), but new File("C:/Data/DataPacket99/data.txt"). Otherwise it will be relative to the current working directory which may not per-se be the same in all environments or the one you'd expect.
You should be using an absolute path instead of a relative path.
You could use File file = new File("C:/Data/DataPacket99/data.txt"); but it might make your life easier in the future to use a file chooser dialog if at any point the user will have to enter a file path.
I would try this:
File file = new File("../../Data/DataPacket99/data.txt");

open resource with relative path in Java

In my Java app I need to get some files and directories.
This is the program structure:
./main.java
./package1/guiclass.java
./package1/resources/resourcesloader.java
./package1/resources/repository/modules/ -> this is the dir I need to get
./package1/resources/repository/SSL-Key/cert.jks -> this is the file I need to get
guiclass loads the resourcesloader class which will load my resources (directory and file).
As to the file, I tried
resourcesloader.class.getClass().getResource("repository/SSL-Key/cert.jks").toString()
in order to get the real path, but this way does not work.
I have no idea which path to use for the directory.
I had problems with using the getClass().getResource("filename.txt") method.
Upon reading the Java docs instructions, if your resource is not in the same package as the class you are trying to access the resource from, then you have to give it relative path starting with '/'. The recommended strategy is to put your resource files under a "resources" folder in the root directory. So for example if you have the structure:
src/main/com/mycompany/myapp
then you can add a resources folder as recommended by maven in:
src/main/resources
furthermore you can add subfolders in the resources folder
src/main/resources/textfiles
and say that your file is called myfile.txt so you have
src/main/resources/textfiles/myfile.txt
Now here is where the stupid path problem comes in. Say you have a class in your com.mycompany.myapp package, and you want to access the myfile.txt file from your resource folder. Some say you need to give the:
"/main/resources/textfiles/myfile.txt" path
or
"/resources/textfiles/myfile.txt"
both of these are wrong. After I ran mvn clean compile, the files and folders are copied in the:
myapp/target/classes
folder. But the resources folder is not there, just the folders in the resources folder. So you have:
myapp/target/classes/textfiles/myfile.txt
myapp/target/classes/com/mycompany/myapp/*
so the correct path to give to the getClass().getResource("") method is:
"/textfiles/myfile.txt"
here it is:
getClass().getResource("/textfiles/myfile.txt")
This will no longer return null, but will return your class.
It is strange to me, that the "resources" folder is not copied as well, but only the subfolders and files directly in the "resources" folder. It would seem logical to me that the "resources" folder would also be found under `"myapp/target/classes"
Supply the path relative to the classloader, not the class you're getting the loader from. For instance:
resourcesloader.class.getClassLoader().getResource("package1/resources/repository/SSL-Key/cert.jks").toString();
In the hopes of providing additional information for those who don't pick this up as quickly as others, I'd like to provide my scenario as it has a slightly different setup. My project was setup with the following directory structure (using Eclipse):
Project/
src/ // application source code
org/
myproject/
MyClass.java
test/ // unit tests
res/ // resources
images/ // PNG images for icons
my-image.png
xml/ // XSD files for validating XML files with JAXB
my-schema.xsd
conf/ // default .conf file for Log4j
log4j.conf
lib/ // libraries added to build-path via project settings
I was having issues loading my resources from the res directory. I wanted all my resources separate from my source code (simply for managment/organization purposes). So, what I had to do was add the res directory to the build-path and then access the resource via:
static final ClassLoader loader = MyClass.class.getClassLoader();
// in some function
loader.getResource("images/my-image.png");
loader.getResource("xml/my-schema.xsd");
loader.getResource("conf/log4j.conf");
NOTE: The / is omitted from the beginning of the resource string because I am using ClassLoader.getResource(String) instead of Class.getResource(String).
When you use 'getResource' on a Class, a relative path is resolved based on the package the Class is in. When you use 'getResource' on a ClassLoader, a relative path is resolved based on the root folder.
If you use an absolute path, both 'getResource' methods will start at the root folder.
#GianCarlo:
You can try calling System property user.dir that will give you root of your java project and then do append this path to your relative path for example:
String root = System.getProperty("user.dir");
String filepath = "/path/to/yourfile.txt"; // in case of Windows: "\\path \\to\\yourfile.txt
String abspath = root+filepath;
// using above path read your file into byte []
File file = new File(abspath);
FileInputStream fis = new FileInputStream(file);
byte []filebytes = new byte[(int)file.length()];
fis.read(filebytes);
For those using eclipse + maven. Say you try to access the file images/pic.jpg in src/main/resources. Doing it this way :
ClassLoader loader = MyClass.class.getClassLoader();
File file = new File(loader.getResource("images/pic.jpg").getFile());
is perfectly correct, but may result in a null pointer exception. Seems like eclipse doesn't recognize the folders in the maven directory structure as source folders right away. By removing and the src/main/resources folder from the project's source folders list and putting it back (project>properties>java build path> source>remove/add Folder), I was able to solve this.
resourcesloader.class.getClass()
Can be broken down to:
Class<resourcesloader> clazz = resourceloader.class;
Class<Class> classClass = clazz.getClass();
Which means you're trying to load the resource using a bootstrap class.
Instead you probably want something like:
resourcesloader.class.getResource("repository/SSL-Key/cert.jks").toString()
If only javac warned about calling static methods on non-static contexts...
Doe the following work?
resourcesloader.class.getClass().getResource("/package1/resources/repository/SSL-Key/cert.jks")
Is there a reason you can't specify the full path including the package?
Going with the two answers as mentioned above. The first one
resourcesloader.class.getClassLoader().getResource("package1/resources/repository/SSL-Key/cert.jks").toString();
resourcesloader.class.getResource("repository/SSL-Key/cert.jks").toString()
Should be one and same thing?
In Order to obtain real path to the file you can try this:
URL fileUrl = Resourceloader.class.getResource("resources/repository/SSL-Key/cert.jks");
String pathToClass = fileUrl.getPath;
Resourceloader is classname here.
"resources/repository/SSL-Key/cert.jks" is relative path to the file. If you had your guiclass in ./package1/java with rest of folder structure remaining, you would take "../resources/repository/SSL-Key/cert.jks" as relative path because of rules defining relative path.
This way you can read your file with BufferedReader. DO NOT USE THE STRING to identify the path to the file, because if you have spaces or some characters from not english alphabet in your path, you will get problems and the file will not be found.
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(fileUrl.openStream()));
I made a small modification on #jonathan.cone's one liner ( by adding .getFile() ) to avoid null pointer exception, and setting the path to data directory. Here's what worked for me :
String realmID = new java.util.Scanner(new java.io.File(RandomDataGenerator.class.getClassLoader().getResource("data/aa-qa-id.csv").getFile().toString())).next();
Use this:
resourcesloader.class.getClassLoader().getResource("/path/to/file").**getPath();**
One of the stable way to work across all OS would be toget System.getProperty("user.dir")
String filePath = System.getProperty("user.dir") + "/path/to/file.extension";
Path path = Paths.get(filePath);
if (Files.exists(path)) {
return true;
}

Categories

Resources