Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get file from project folder java

Tags:

java

file

I want to get File from project folder by using "File class", How can I do that?

File file=new File("x1.txt"); 
like image 868
Saad Ahmad Avatar asked Jun 25 '13 00:06

Saad Ahmad


People also ask

How do you reference a file in Java?

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.

How do you load properties file from resources folder in Java?

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().

How do I read a file from SRC main resources?

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.

What is getAbsolutePath in Java?

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.


1 Answers

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!

like image 113
Singular1ty Avatar answered Sep 22 '22 06:09

Singular1ty