getting the path input file at run time - java

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

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.

Error trying to read from a text file [duplicate]

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

How to get absolute path of existing folder

I have a test data folder in my java project... something like this
Project
src Folder
testData Folder
How can I get the data folder using java, previously we have a hardcoded the in a constant, but now we are using a CI tool and I want to avoid the hardcoded path.
its is very fine to hardcode the testdata folder, but the
point is that it should be a relative path:
At the top of the test class you can just write
static final String TEST_PATH = "./testdata/";
Note that this is relative to the project.
If you want to convert such a relative path to an absoulte one:
String absoluteTestPath = new File(TEST_PATH).getAbsolutePath();
Take the input parameter and create a new File Object. The Java file object will provide getPath(), getAbsolutePath(), and getCanonicalPath(). Be careful with the file systems. If you are swapping between Windows/Linux/Mac/etc, you may have issues with translating paths between source and destination. I assume you source and destination are on the same file system in the example below.
File f = new File(pathStr);
String absPath = f.getAbsolutePath();
How about using Paths?
Paths.get("your-relative-path-here").toAbsolutePath()
Well, I solved my issue in the following way
public static final String Path_TestData = System.getProperty("user.dir") + "\\TestData\\";
For src
static String SRC_PATH = new File(".").getCanonicalPath()+System.getParameter("file.separator")+SRC;
// where SRC is the name of your source folder
For testdata:-
static String TEST_PATH = "./testdata/";

how to get full path of the current file including the src file in java

I have a file dateTesting.java . the path's directory is as follows: D:\workspace\Project1\src\dateTesting.java . I want the full path of this file as "D:\workspace\Project1\src" itself but when I use any of the following code, i get only "D:\workspace\Project1" . the src part is not coming.
System.out.println(System.getProperty("user.dir"));
File dir2 = new File(".");
System.out.println(dir2.getCanonicalPath().toString());
System.out.println(dir2.getAbsolutePath());
How can I get the full path as "D:\workspace\Project1\src" ? I'm using eclipse ide 3.5
Thank you
dateTesting.java is a Java source file which is not available after compilation to bytecode. The source directory it was in is not available, too.
dir2 is the File of the directory you execute the .class file in. It seams that this happens to be D:\workspace\Project1 but you can't rely on this.
Your dir2 points to working directory (new File(".")). You can't get the location of your sources this way. Your file could sit inside the package (e.g. your.company.date.dateTesting). You should just manually concat the "src" to current working directory and then replace file package dots (.) with File.pathSeparator. In that way you will build the full path to your file.
String fullFilePath = "H:\\Shared\\Testing\\abcd.bmp";
File file = new File(fullFilePath);
String filePath = file.getAbsolutePath().substring(0,fullFilePath.lastIndexOf(File.separator));
System.out.println(filePath);
Output:
H:\Shared\Testing
If you are doing this to try to read a file from the classpath, then check out this answer:
How to really read text file from classpath in Java
Essentially you can do this
InputStream in = this.getClass().getClassLoader()
.getResourceAsStream("SomeTextFile.txt");
Otherwise, if you have some other requirement, one option is to pass through the src directory as a JVM arg when the application begins and then just read it back.
/** The actual file running */
public static final File JAR_FILE = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath();
/** The path to the main folder where the file .jar is run */
public static final String BASE_DIRECTORY = (JAR_FILE != null ? JAR_FILE.getAbsolutePath().replace(JAR_FILE.getName(), "") : "notFound");
This will work for you both in normal java execution and jar execution. This is the solution I am using in my project.

Create File object of file from parent directory in java

I have this issue of accessing a file in one of the parent directories.
To explain, consider the following dir structure:-
C:/Workspace/Appl/src/org/abc/bm/TestFile.xml
C:/Workspace/Appl/src/org/abc/bm/tests/CheckTest.java
In the CheckTest.java I want to create a File instance for the TestFile.xml
public class Check {
public void checkMethod() {
File f = new File({filePath value I want to determine}, "TestFile.xml");
}
}
I tried a few things with getAbsolutePath() and the getParent() etc but was getting a bit complicated and frankly I think I messed it up.
The reason I don't want to use "C:/Workspace/Appl/src/org/abc/bm" while creating the File instance is because the C:/Workspace/Appl is not fixed and in all circumstances will be different at runtime and basically I don't want to hard-code.
What could be the easiest and cleaner way to achieve this ?
Thank you.
You should load it from Classpath in this case.
In your CheckTest.java, try
FileInputStream fileIs = new FileInputStream(CheckTest.class.getClassLoader().getResourceAsStream("org/abc/bm/TestFile.xml");
Use System.getProperty to get the base dir or you set the base.dir during application launch
java -Dbase.dir=c:\User\pkg
System.getProperty("base.dir");
and use
System.getProperty("file.separator");
What could be the easiest and cleaner way to achieve this ?
For accessing static resources use:
URL urlToResource = this.getClasS().getResource("path/to/the.resource");
If the resource is expected to change, write it to a sub-directory of user.home, where it is easy to locate later.
First of all, you can't get a reference to the source file path on runtime.
But, you can access the resrources included at your classpath (where you complied .class files will be).
Normally, your compiler will copy the xml file included at your srouce directory into the build directory, so at last, you could end up having something like this:
C:/Workspace/Appl/classes/org/abc/bm/TestFile.xml
C:/Workspace/Appl/classes/org/abc/bm/tests/CheckTest.class
Then, with your classpath pointing to the compiled classes root dir, you get the resources from this directory, using the ClassLoader.getResource method (or the equivalent Class.getResource() method).
public class Check {
public void checkMethod() {
java.net.URL fileURL=this.getClass().getResource("/org/abc/bm/tests/TestFile.xml");
File f=new File( fileURL.toURI());
}
}
One could do this:
String pathOfTheCurrentClass = this.getClass().getResource(".").getPath();
File file = new File(pathOfTheCurrentClass + "/..", "Testfile.xml");
or
String pathOfTheCurrentClass = this.getClass().getResource(".").getPath();
File filePath = new File(pathOfTheCurrentClass);
File file = new File(filePath.getParent(), "Testfile.xml");
But as Tomas Naros points out this gives you the file located in the build path.
Did you try
URL some=Test.class.getClass().getClassLoader().getResource("org/abc/bm/TestFile.xml");
File file = new File(some.getFile());

Categories