I want to get File from project folder by using "File class", How can I do that?
File file=new File("x1.txt");
File myFile = new File("com\\company\\somePackage\\MyFile. txt"); the jar file correctly locates the file, but running locally (Run As->Java Main application) throws a file not found exception because it expects it to be: File myFile = new File("src\\com\\company\\somePackage\\MyFile.
In Java, we can use getResourceAsStream or getResource to read a file or multiple files from a resources folder or root of the classpath. The getResourceAsStream method returns an InputStream . // the stream holding the file content InputStream is = getClass(). getClassLoader().
Using Java getResourceAsStream() This is an example of using getResourceAsStream method to read a file from src/main/resources directory. First, we are using the getResourceAsStream method to create an instance of InputStream. Next, we create an instance of InputStreamReader for the input stream.
The getAbsolutePath() method is a part of File class. This function returns the absolute pathname of the given file object. If the pathname of the file object is absolute then it simply returns the path of the current file object. For Example: if we create a file object using the path as “program.
Well, there are many different ways to get a file in Java, but that's the general gist.
Don't forget that you'll need to wrap that up inside a try {} catch (Exception e){}
at the very least, because File is part of java.io
which means it must have try-catch block.
Not to step on Ericson's question, but if you are using actual packages, you'll have issues with locations of files, unless you explicitly use it's location. Relative pathing gets messed up with Packages.
ie,
src/ main.java x.txt
In this example, using File f = new File("x.txt");
inside of main.java
will throw a file-not-found exception.
However, using File f = new File("src/x.txt");
will work.
Hope that helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With