the print of getAbsolutePath in Java - java

My development environment: Mac + IntelliJ Idea.
I'm practicing the File class in Java.
public class FileDemo {
public static void main(String[] args) throws IOException {
File file = new File("/Users/Samuel/IdeaProjects/JavaFundamentals/src/aa/bb/test.txt");
file.createNewFile();
System.out.println(file.getAbsolutePath());
}
}
the result is /Users/Samuel/IdeaProjects/JavaFundamentals/src/aa/bb/test.txt
It's OK.But after I changed the path,the print became strange.
public class FileDemo {
public static void main(String[] args) throws IOException {
File file = new File("test.txt"); //notice this line
file.createNewFile();
System.out.println(file.getAbsolutePath());
}
}
the print is /Users/Samuel/IdeaProjects/test.txt
I'm confused of the path.

Because "test.txt" is a relative path and the file will be created relative to the program's working directory (in this case /Users/Samuel/IdeaProjects/).

In the first case you have provided the full path in your initialization. So it is printing the full path. In the second case, you are using relative paths. The base path for that is home directory of your project.

1) When you provide the full path in File class constructor while creating the File object then it will create the file on mentioned path.
2) But In case you are not providing the full path then it will create the File on the same path where your .class file is. It is relative path.

Your project folder is the main folder for the File class. This is where the File class starts from. If you want a lower folder you need te specify your path or you can use: "new File("../");
The main reason why it is in the folder "IdealProjects" is, because this is the start path of your project.

Related

Incorrect Absolute File Path

I need a relative path for a csv file I have called GameDatabase.csv. It is in the same folder as my main method which are both in zzz folder.
The file kept turning up not found so I decided to print the absolute path
String db = "GameDatabase.csv";
File file = new File(db);
String path = file.getAbsolutePath();
System.out.print("\npath " + path);
The output is
path xxx\IdeaProjects\CISC_231\FinalProject\GameDatabase.csv
However the path that I am looking for is
xxx\IdeaProjects\CISC_231\FinalProject\zzz\GameDatabase.csv
Why is the absolute file path printing this out? What is going on in the background and how can I change it to get the correct file path?
That is because, when you look for a file, the default directory is the project one (in this case FinalProject)
I structured the project as follows
Main.java and GameDatabase.csv are both in src
import java.io.File;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
System.out.println(new File("GameDatabase.csv").exists()); // the file does not exist in FinalProject folder
System.out.println(new File("src/GameDatabase.csv").exists()); // but exists in FinalProject/src
System.out.println(Main.class.getClassLoader().getResourceAsStream("GameDatabase.csv").toString()); // this is a solution to look for the file within the classpath
}
}
The output is
false
true
java.io.BufferedInputStream#7852e922
String db = "GameDatabase.csv";
File file = new File(db)
You can create a File object representing a file that doesn't actually exist. What you have done is creating a File object representing the file "GameDatabase.csv" in the current working directory (this file does not exist) and then you printed the absolute path it would have if it existed.

How to determine correct path to open a file with PrintWriter?

When creating a PrinterWriter object:
PrintWriter outputFile = new PrintWriter(*FileName*);
Where is the compiler looking when it goes to find FileName? For example, in Eclipse I am working in Arrays/src/ArraysAndFiles.java. In this example I am trying to open Values.txt. I have created this file in the src directory since that is where ArraysAndFiles.java is stored. When I attempt to open the file in the following code I get a FileNotFoundException:
import java.io.PrintWriter;
public class ArraysAndFiles {
public static void main(String[] args) {
// TODO Auto-generated method stub
PrintWriter outputFile = new PrintWriter("Values.txt");
}
}
What is the proper path to Values.txt?
Solution #1 (recommended for small files but you have the benefit that file will be found in other computers as well): How do I load a file from resource folder?
Solution #2: Build the path step by step by using File(String parent, String child) constructor. Example:
File desktop = new File(System.getProperty("user.home"),"Desktop");
File textsFolder = new File(desktop,"texts");
File testsFolder = new File(textsFolder,"tests");
File peopleTxt = new File(testsFolder,"people,txt");
Which is equals to: C://Users//George//Desktop//texts//tests//people.txt (Windows OS).
As per code,
PrintWriter outputFile = new PrintWriter("Values.txt");
if you place your Values.txt in current/project directory i.e. in Arrays folder it should work but there are limitation as mentioned in above comments like writing to the file which is a part of JarFile.
Depending upon your purpose, you should take the action.
In your example "Values.txt" is a relative path. It's relative to your working directory.
Usually it's the same directory where your JAR file resides.
In Eclipse an application is built in the 'bin' folder. In your case it's Arrays\bin\. So this is the working directory for the application and your file has to be there.
If you want Eclipse to export this file during the Build process, do the following:
Right click on the file -> Build Path -> Add to Build Path

Access to resource missing with an exported jar file

If I run the following code within eclipse my program compiles with no issue. If I try to export the program as a runnable jar file my resource cannot be found.
public class Test {
public static void main(String[] args) {
File file = new File(Tester.class.getClassLoader().getResource("res/myFile.txt").getFile());
if(!file.exists()) { System.out.println("File not found."); }
}
}
Folder structure (by running jar tf test.jar):
com/
com/test/
com/test/Tester.class
res/
res/myFile.txt
There is no such file in case of jar.
Use instead Tester.class.getResourceAsStream("/myFile.txt") and work with the stream
UPDATE:
See more here or here

path defined in linux style a final variable. Can't open the path on windows

I don't know what to search for.
I have a external jar library in which there is a class that has all the configurations variables like where to store the log files and such, as public static final variables.
the path for log file config given is "/home/log.cfg".
Now I am working in windows. How do I make a path like this? where to put the cfg file?
The file can still be opened an read if you create the directory home in the root of your drive. Just make sure that the working directory of the application is on the same drive. Java file handling API seems to add the dirve letter to an absolute path if none was specifyed.
javadoc for File#getAbsolutePath
On Microsoft Windows systems, a relative pathname is made absolute by resolving it against the current directory of the drive named by the pathname, if any; if not, it is resolved against the current user directory.
A simple test demonstrates that:
Create a directory under C:\ named home and place some text file inside.
#Test
public void openFile() throws FileNotFoundException, IOException {
File file = new File("/home/log.cfg");
System.out.println(file.getAbsolutePath());
FileInputStream fileInputStream = new FileInputStream("/home/log.cfg");
int c;
while(-1 != (c = fileInputStream.read())) {
System.out.print((char) c);
}
fileInputStream.close();
}
And here is the output:
C:\home\log.cfg
Hello, log.fg!

getting the path input file at run time

I have my main class a one more class which takes a file path(absolute) as string. How can i initialize this filepath with its value. No hard codeing of the path of file is required.
My package stcture is
src
com.xyz.pk1
data //input.txt is present in this dir
public class Test{
public static void main(){
String filepath = "" //TODO :no hard coding like C:\filename.txt
MyClass c = new new Myclass(filepath);
}
}
EDIT:
My folder struct is as follows NOW:
src
data
input.txt
now if i type following code inside a class placed in src
Test.class.getResourceAsStream("data/Input.csv");
I get error
Exception in thread "main" java.lang.NullPointerException
at java.io.Reader.<init>(Reader.java:61)
at java.io.InputStreamReader.<init>(InputStreamReader.java:55)
any clues??
This will return the absolute path of the file
File f = new File("<your file>");
String path = f.getAbsolutePath();
You probably will not have a src dir after building. It will be classes or bin or such. If your data is static the resources folder should be merged with the classes folder (this is the default for Maven).
I.e. the structure could be:
/
com
xyz
pk1
Test.class
data
input.txt
Then you could get an URL pointing to the resource with
YourClassName.class.getResource("/data/input.txt");
or an InputStream with
YourClassName.class.getResourceAsStream("/data/input.txt");
That is the way to go for static resources. You can even package the resource within a jar. If you want to modify the file than it would be the wrong method.
You many Choose JFileChooser to select your file and then set
JFileChooser chooser=new JFileChooser();
and
then
File file=chooser.getSelectedFile();

Categories