Hi I need to read the file by using FileInputStream but I didn\'t get the right path. My file is location at C:\\Users\\tester\\Documents\\Java Project\\Samples\\ProjectOne\\src
You can create file
and use getAbsolutePath
method:
File file = new File("TestFile.txt");//full file path URL
String absolutePath = file.getAbsolutePath();
Here is the simple programme:
public static void main(String[] args) {
File f = null;
String path = "";
boolean bool = false;
try {
// create new files
f = new File("test.txt");
// returns true if the file exists
bool = f.exists();
// if file exists
if (bool) {
// get absolute path
path = f.getAbsolutePath();
// prints
System.out.print("Absolute Pathname " + path);
}
} catch (Exception e) {
// if any error occurs
e.printStackTrace();
}
}
You are probably using Eclipse and as you have saved the file TestFile.txt
inside your source folder, it is being copied to the bin
folder, the output folder of your project. Therefore, the path is not wrong. As in your code you use getResource
method, the file will be retrieved from the same directory where your MainForm.class
was found.
http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getResource(java.lang.String)
If you really want to get such file from your source folder, then you should do something like this:
System.out.println(new File("src/pdfReader/TestFile.txt").getAbsolutePath());
However, if you are planning to distribute your application it would be better to store this kind of file in a resources
folder because source folders are usually not included in dist
packages.