Read file from another package - Java - java

I'm trying to access a file from another package:
-Using LoadDatabase from Main package to access DB.txt from resources.
Image Here
When I do
File file = new File("/com/Convocatoria/resources/DB.txt");
Scanner sc = new Scanner(file);
It gives me this error
Unhandled exception type FileNotFoundException

Don't Use absolute path use getResourceAsStream method
I dont know which IDE you are using if you specify the path like this it jvm will look for file from the root of your project but your file is precent in your rootproject->src->under some packages so it is best to use getResouceAsStream because when you build it or run it all the .class files and property files will go under the class path so we know that our file will be in classpath So we can easily read the file using getResourceAsStream for eg:-
you are reading the file from MainWindow.java class
use the below code
InputStream is =MainWindow.class.getResourceAsStream("/Convocatoria/resources/DB.txt")
from this inputstream you use FileInputStream or whatever you want to read the file

Since you are loading data from within your classpath, you can use resources instead:
String resourceName = "/com/Convocatoria/resources/DB.txt";
URL res = LoadDatabase.class.getResource(resourceName);
System.out.println("resource found at url="+res);
InputStream is = LoadDatabase.class.getResourceAsStream(resourceName);
Scanner s = new Scanner(is);
//read..
//after using it, close your stream
is.close();

File constructor will throw a FileNotFoundException when it fails to find the file with specific path. You need to surround it with a try-catch block that catches the mentioned exception:
File file = null;
Scanner sc = null;
try{
file = new File("/com/Convocatoria/resources/DB.txt");
sc = new Scanner(file);
// do something with opened file
} catch(FileNotFoundException ex){
ex.printStackTrace();
}

Related

How to get path of java files including /src/

im Working on a project that can compile/run existing java files in PC.
most of code works pretty well, but im having a problem at getting the path of java files.
here are the problematic codes
void uploadJ() {
System.out.print("Insert File name : "); //ex)HelloWorld.java
FileName = sc.next();
}
void Compile(){
String s = null;
File file = new File(FileName);
String path = file.getAbsolutePath();
try {
Process oProcess = new ProcessBuilder("javac", path).start();
BufferedReader stdError = new BufferedReader(
new InputStreamReader(oProcess.getErrorStream()));
while ((s = stdError.readLine()) != null) {
FileWriter fw = new FileWriter(E_file, true);
fw.write(s);
fw.flush();
fw.close();
}
} catch...
}
For instance, when i put HelloWorld.java as a file name,
the absolute path of the HelloWorld.java should be C:\Users\user\eclipse-
workspace\TermProject\src\HelloWorld.java,
but instead, the result is C:\Users\user\eclipse-
workspace\TermProject\HelloWorld.java.
it misses /src/ so it always ends up with javac: file not found error.
When your application has been compiled, there will be no src directory. This working directory could also be set to anything.
You also can't guarantee that the file you are looking for is an actual file, in the context of a jar file, it isn't.
However, you can load files from the classpath. You can make use of Class#getResourceAsStream(String):
Finds a resource with a given name. The rules for searching resources associated with a given class are implemented by the defining class loader of the class.`.
Finding the file can be accomplished by calling this.getClass().getResourceAsStream("/" + FileName), with the / causing the search to occur from the resource root.
To use this with javac, you'll have to create a temporary file and populate it with the data stream you get from getResourceAsStream.

How do I create a File object in Java w/out using an absolute path name?

This is the path I'm using now:
C:\Users\Sabrina\Documents\NetBeansProjects\TriangleSumRecursion\lab4Data.txt
I tried just using the following:
C:\TriangleSumRecursion\lab4Data.txt
and
TriangleSumRecursion\lab4Data.txt
If I use either of those two Java will say "(The system cannot find the file specified)"...
TriangleSumRecursion is the java package that I'll turn in.
You can import the particular file into the project, and then try using TriangleSumRecursion\lab4Data.txt
You can import the file by right clicking on your project folder from your IDE, and then click on import. Follow the instructions and give the path of your file in it.
i hope it works for you.
First of all, use Slashes ('/'), not Backslashes ('\') in Javacode.
But besides of that, Java can handle absolute and relative paths.
I tried just using the following: C:\TriangleSumRecursion\lab4Data.txt
This is not the right absolute path, if there is no folder 'TriangleSumRecursion' in C:\. Your working path example is the only right one.
and TriangleSumRecursion\lab4Data.txt
Here you try this as a relative path. Java starts its search in the folder your file, running the code, is located. So this would work, if your java file was in 'C:\Users\Sabrina\Documents\NetBeansProjects'.
But since I think your file is in 'TriangleSumRecursion', the path you are looking for is simply 'lab4Data.txt'.
You could try the following reading your file line by line, by first reading the file through a file reader, that is then fed to the buffered reader. Then you can create a string buffer, and as the program reads each line of the file it will append it to the string buffer. To check if it was successful just simply close the file reader and use the toString() method to display the contents of the file.
`public static void main(String[] args) {
try {
File file = new File("lab4Data.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
stringBuffer.append("\n");
}
fileReader.close();
System.out.println("File is:");
System.out.println(stringBuffer.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}`
C:\TriangleSumRecursion\lab4Data.txt is an absolute path, so this will not identify your file which is not at this location.
You are more than probably in directory C:\Users\Sabrina\Documents\NetBeansProjects\TriangleSumRecursion, therefore a simple:
Paths.get("lab4Data.txt")
will give you a Path to your file (this is 2015; use java.nio.file and drop File).
But this is Windows and there are some strange things with Windows... Another way to access your file would be:
Paths.get("c:lab4data.txt")
Which is a path which has a root (c:) but which is not absolute (since such a path cannot be used to uniquely identify a resource on the FileSystem.
See the Files class on how to open, for instance, an InputStream or a BufferedReader from this file. And note that if the file does not exist the matching methods will throw a NoSuchFileException.
Last but not least, use a try-with-resources statement:
try (
final BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8);
) {
// use the reader here
}

What is the root place of FileReader searching for files?

I've tried to load file to use by scanner like this:
try {
Scanner scanner = new Scanner(new FileReader("map.txt"));
}catch (FileNotFoundException e) {
e.printStackTrace();
}
But I get the FileNotFoundException error even thought I place map.txt file in class folder. Also I created special folder and marked it as a resources root in IntelliJ IDEA but still it doesn't work. How can I know where FileReader is searching for file then?
This might help you. Use File#getAbsolutePath() to check for the path.
File reader = new File("abc.txt");
System.out.println(reader.getAbsolutePath());
Some more ways to read from project
// Read from resources folder parallel to src in your project
File file1 = new File("resources/abc.txt");
System.out.println(file1.getAbsolutePath());
// Read from src/resources folder
File file2 = new File(getClass().getResource("/resources/abc.txt").toURI());
System.out.println(file2.getAbsolutePath());

Load file dynamically from jar

I am trying to read a .json file I am packaging with my .jar.
The problem - finding the file so that I can parse it in.
The strange bit is that this code works in NetBeans, likely due to the way these methods work and the way NetBeans handles the dev workspace. When I build the jar and run it, however, it throws an ugly error: Exception in thread "main" java.lang.IllegalArgumentException: URI is not hierarchical.
My code for getting the file is as such:
//get json file
File jsonFile = new File(AndensMountain.class.getResource("/Anden.json").toURI());
FileReader jsonFileReader;
jsonFileReader = new FileReader(jsonFile);
//load json file
String json = "";
BufferedReader br = new BufferedReader(jsonFileReader);
while (br.ready()) {
json += br.readLine() + "\n";
}
I have gotten it to work if I allow it to read from the same directory as the jar, but this is not what I want - the .json is in the jar and I want to read it from in the jar.
I've looked around and as far as I can see this should work but it isn't.
If you are interested, this is the code before trying to get it to read out of the jar (which works as long as Anden.json is in the same directory as AndensMountain.jar):
//get json file
String path = AndensMountain.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath();
File jsonFileBuilt = new File(new File(path).getParentFile(), "Anden.json");
File jsonFileDev = new File(new File(path), "Anden.json");
FileReader jsonFileReader;
try {
jsonFileReader = new FileReader(jsonFileBuilt);
} catch (FileNotFoundException e) {
jsonFileReader = new FileReader(jsonFileDev);
}
Try
Reader reader = new InputStreamReader(AndensMountain.class.getResourceAsStream("/Anden.json"), "UTF-8");
AndensMountain.class.getResource("/Anden.json") URL when ran outside a jar (for example, when the classes are compiled to a "classes/" directory) is a "file://" URL.
That is not the case when ran from inside a jar: it then becomes a "jar://" URL.
The java.io.File doesn't know how to handle this type of URL. It handles only "file://".
Anyway you don't really need to treat it as a File. You can manipulate the URL itself (either to navigate to a parent directory, for example) or to get its contents (via openStream(), or if you need to add headers, via openConnection()).
java.lang.Class#getResourceAsStream() as I suggested is just shorthand to Class#getResource() followed by openStream() on its result.

How to link a local file

I'm trying to use a local file in which I've specified my db connection properties which is named dao.properties. And I'm proceeding this way:
InputStream fichierProperties = classLoader.getResourceAsStream( "/src/dao/dao.properties" );
However, when using this path, I'm getting an exception stating that the debugger wasn't able to find that file.
Here are some packages in my project:
The dao.properties is just under the dao package.
How do I resolve this, please?
If you put the file inside the src folder, the IDE probably is packaging, when instructed to compile and build, the file into the bundled generated jar. So you can reach with the method GetResourceAsStream.
So if you put the file (dao.properties) in root folder of your sources files (generally the src folder), just simple referring to dao.properties will refer to the resource.
If you put the file inside a subfolder of src, the correct way to reference it would be subfolder/dao.properties.
The first "/" is not necessary as the getResourceAsStream always search in the classpath, that for default is the root of the sources folder, inside the jar. (where are not talking about external files!)
Updated:
Assuming you place a file name notes.txt inside a folder(package) named ´sub´, this is valid example, only for purporses of how to get a bundled file that is in jar.
public class Main {
public static void main (String[] args) throws IOException {
InputStream is = Main.class.getResourceAsStream("sub/notes.txt");
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
while (s != null) {
System.out.println (s);
s = br.readLine();
}
is.close();
}
}
I add more information about this, by referring to this post

Categories