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.
Related
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
I have a file named "word.txt".
It is in the same directory as my java file.
But when I try to access it in the following code this file not found error occurs:
Exception in thread "main" java.io.FileNotFoundException: word.txt
(The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.util.Scanner.<init>(Unknown Source)
at Hangman1.main(Hangman1.java:6)
Here's my code:
import java.io.File;
import java.util.*;
public class Hangman1 {
public static void main(String[] args) throws Exception {
Scanner input = new Scanner(new File("word.txt"));
String in = "";
in = input.nextLine();
}
}
Put the word.txt directly as a child of the project root folder and a peer of src
Project_Root
src
word.txt
Disclaimer: I'd like to explain why this works for this particular case and why it may not work for others.
Why it works:
When you use File or any of the other FileXxx variants, you are looking for a file on the file system relative to the "working directory". The working directory, can be described as this:
When you run from the command line
C:\EclipseWorkspace\ProjectRoot\bin > java com.mypackage.Hangman1
the working directory is C:\EclipseWorkspace\ProjectRoot\bin. With your IDE (at least all the ones I've worked with), the working directory is the ProjectRoot. So when the file is in the ProjectRoot, then using just the file name as the relative path is valid, because it is at the root of the working directory.
Similarly, if this was your project structure ProjectRoot\src\word.txt, then the path "src/word.txt" would be valid.
Why it May not Work
For one, the working directory could always change. For instance, running the code from the command line like in the example above, the working directory is the bin. So in this case it will fail, as there is not bin\word.txt
Secondly, if you were to export this project into a jar, and the file was configured to be included in the jar, it would also fail, as the path will no longer be valid either.
That being said, you need to determine if the file is to be an embedded-resource (or just "resource" - terms which sometimes I'll use interchangeably). If so, then you will want to build the file into the classpath, and access it via an URL. First thing you would need to do (in this particular) case is make sure that the file get built into the classpath. With the file in the project root, you must configure the build to include the file. But if you put the file in the src or in some directory below, then the default build should put it into the class path.
You can access classpath resource in a number of ways. You can make use of the Class class, which has getResourceXxx method, from which you use to obtain classpath resources.
For example, if you changed your project structure to ProjectRoot\src\resources\word.txt, you could use this:
InputStream is = Hangman1.class.getResourceAsStream("/resources/word.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
getResourceAsStream returns an InputStream, but obtains an URL under the hood. Alternatively, you could get an URL if that's what you need. getResource() will return an URL
For Maven users, where the directory structure is like src/main/resources, the contents of the resources folder is put at the root of the classpath. So if you have a file in there, then you would only use getResourceAsStream("/thefile.txt")
Relative paths can be used, but they can be tricky. The best solution is to know where your files are being saved, that is, print the folder:
import java.io.File;
import java.util.*;
public class Hangman1 {
public static void main(String[] args) throws Exception {
File myFile = new File("word.txt");
System.out.println("Attempting to read from file in: "+myFile.getCanonicalPath());
Scanner input = new Scanner(myFile);
String in = "";
in = input.nextLine();
}
}
This code should print the folder where it is looking for. Place the file there and you'll be good to go.
Your file should directly be under the project folder, and not inside any other sub-folder.
If the folder of your project is named for e.g. AProject, it should be in the same place as your src folder.
Aproject
src
word.txt
Try to create a file using the code, so you will get to know the path of the file where the system create
File test=new File("check.txt");
if (test.createNewFile()) {
System.out.println("File created: " + test.getName());
}
I was reading path from a properties file and didn't mention there was a space in the end.
Make sure you don't have one.
Make sure when you create a txt file you don't type in the name "name.txt", just type in "name". If you type "name.txt" Eclipse will see it as "name.txt.txt". This solved it for me. Also save the file in the src folder, not the folder were the .java resides, one folder up.
I have the same problem, but you know why? because I didn't put .txt in the end of my File and so it was File not a textFile, you shoud do just two things:
Put your Text File in the Root Directory (e.x if you have a project called HelloWorld, just right-click on the HelloWorld file in the package Directory and create File
Save as that File with any name that you want but with a .txt in the end of that
I guess your problem is solved, but I write it to other peoples know that.
Thanks.
i think it always boils to the classpath. having said that if you run from the same folder where your .class is then change Scanner input = new Scanner(new File("word.txt")); to Scanner input = new Scanner(new File("./word.txt")); that should work
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.
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!
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();