java file relative path in eclipse - java

Three days i was trying to figure out how to read file using relative file path. In eclipse this compiles and works great, but when i export app. It says that it can't find the file. here is the screenshot and code i work on.
This code works, but only in eclipse, it compiles and does job perfectly. But when i export it as as runnable jar file i get an error, that it cannot locate licenca.txt
BufferedReader in = new BufferedReader(new FileReader(new File("licenca.txt").getPath()));
String str;
while ((str = in.readLine()) != null) {
taLicenca.append(str + "\n");
}
here is the screenshot of my project files
i have tried use of scanner function, still the same result, it works in eclipse, but doesn't work on export. Here is the error message:

I'll bet it'll work if you put that file into the classpath.
Change your code like this:
InputStream is = this.getClass().getClassLoader().getResourceAsStream("licenca.txt");
BufferedReader in = new BufferedReader(new InputStreamReader(is));
String str;
while ((str = in.readLine()) != null) {
taLicenca.append(str + "\n");
}
Try it and see.

It happens because your file is exported as part of jar file, so, for creating jar file try to use ant or maven or semething else, or manually copy your file in directory with with your jar, it calls start directory.

Related

JAR file doesn't recognize update of a file that I'm reading in JAR

I'm using Netbeans and in my program I'm reading a file. When I run the program it reads the file correctly. When I build the program the JAR also works correctly. But when I change the file that I am reading from, in my build dir, my JAR doesn't update accordingly. Why is that so? Is there a solution for this?
The code below shows how am I reading the file in my program. Thanks in advance.
InputStream in = NewJFrame.class.getResourceAsStream("/holidays.txt");
BufferedReader readHolidays = new BufferedReader(new InputStreamReader(in));
String line;
line = readHolidays.readLine();
while(line != null) {
//read into hashmaps
//...
line = readHolidays.readLine();
}
readHolidays.close();
Never mind, i got it ;) If anyone else needs this: Basically every time i run the program i find the file path to the jar file and from there i read text document.
File jarFile = new File(this.getClass().getProtectionDomain().getCodeSource().getLocation().toURI());
FileInputStream is = new FileInputStream(jarFile.getParent().toString() + "/file.txt"); BufferedReader readFile= new BufferedReader(new InputStreamReader(is));

Displaying a text file on a webpage

I'm new to coding and have decided to start my learning on Java. I've got NetBeans and have started to create a very basic web application. I'd like to be able to display values from a .txt file onto the webpage, and I've got this code to do so.
<%
BufferedReader in = new BufferedReader(new FileReader("Cats.txt"));
String line;
while((line = in.readLine()) != null)
{
out.println(line);
}
in.close();
%>
My text file is in the same folder as my src folder (As I've seen you need to put the file)
However, whenever I navigate to the web page I get a FileNotFound error. I've tried placing the files path in the FileReader but that gives an error due to the backslashes.
If anyone could help I'd be greatly appreciated
Currently it's looking for the file in the src directory of your application you should just be able move the file there and it should read it. If you would like to direct to a specific path you need to tell the IDE to treat the '\' as a normal slash to do this you need to close it off by using two '\'s instead of one eg:
<%
BufferedReader in = new BufferedReader(new
FileReader("C:\\MYPATH\\MYPATH2\\Cats.txt"));
String line;
while((line = in.readLine()) != null)
{
out.println(line);
}
in.close()
%>

Unable to read the file in Eclipse

I have a project in our university and in order to make it we have to read a txt file(in java,eclispe). I take the file and drag and drop (the method which reads the file they gave it ready to us) but when I run the program it gives me this:
I do not know if the mistake is how I put the file in the Eclipse
The folder name above src is non-English so I can't type it out, but suppose it were just Laur155. Suppose that this folder is directly under ~/workspace. Then to open the file you would do
String filename = "~/workspace/Laur155/NBA-5d-17265n.txt";
then something like
BufferedReader reader = new BufferedReader(new FileReader(filename));
String line;
while ((line = reader.readLine()) != null) { ...
No we must not change the code in the method which reads the txt file
I know maybe i confuse you but in my university they havent teach as nothing about files

java reading text from src without writing a long path

I can read texts and write them to console however when i install this application to another computer wherever it is installed I dont want to change the path of the txt file. I want to write it like
BufferedReader in = new BufferedReader(new FileReader("xxx.txt"));
I don't want to:
BufferedReader in = new BufferedReader(new FileReader("C:\\Users\\abcde\\Desktop\\xxx.txt"));
is there any way to show this txt file? By the way I put this txt file inside the sources but it cant read!
First get the default application path then check if file exist if exist continue if not close application.
String path = System.getProperty("user.dir");
System.out.println(path + "\\disSoruCevap.txt");
File file = new File(path + "\\disSoruCevap.txt");
if (!file.exists()) {
System.out.println("System couldnt file source file!");
System.out.println("Application will explode");
}
EDIT*
Please prefer one of the answer using resource streams, as you will
see from comments using user.dir is not safe in every case.
You are looking for :
BufferedReader in = new BufferedReader(getClass().getResourceAsStream("/xxx.txt"));
This will load xxx.txt from your jar file (or any jar file in your class path that has that file inside its root directory).
URL fileURL= yourClassName.class.getResource("yourFileName.extension");
String myURL= fileURL.toString();
now you don't need long path name PLUS this one is dynamic in nature i.e., you can now move your project to any pc, any drive.This is because it access URL by using your CLASS location not by any static location (like c:\folder\ab.mp3, then you can't access that file if you move to D drive because then you have to change to D:/folder/ab.mp3 manually which is static in nature)(NOTE: just keep that file with your project)
You can use fileURL as: File file=new File(fileURL.toURI());
You can use myURL as: Media musicFile=new Media(myURL); //in javaFX which need string not url of file
InputStream input = Class_name.class.getResourceAsStream("/xxx.txt");
InputStreamReader inputReader = new InputStreamReader(input);
BufferedReader br = new BufferedReader(inputReader);
String line = null;
try {
while((line = br.readLine())!=null){
System.out.println(line);
}
} catch (IOException ex) {
ex.printStackTrace();
}
You don't need to write or mention long path. Using this code Class_name.class.getResourceAsStream("/xxx.txt"), you can easily get your file.
BufferedReader in = new BufferedReader(new FileReader("xxx.txt")); works fine because when you run your application on an IDE, xxx.txt apparantly is lying in Java's working directory.
Working directory is an operating system feature and it can not be changed.
There are a few ways to deal with this.
1 - use file constructor new File(parent, filename); and load parent using a public static final constant or a property (either passed from command line or otherwise)
2 - or use InputStream in = YourClass.class.getClassLoader().getResourceAsStream("xxx.txt"); - provided your xxx.txt file is packaged under same location as YourClass
Try:
InputStream is = ClassLoader.getSystemResourceAsStream("xxx.txt");
BufferedReader in = new BufferedReader(new InputStreamReader(is));
Depending on where exactly is your file compared to the root of your classpath, you may have to replace xxx.txt3 with /xxx.txt.
My file paths are like this:
public final static String COURSE_FILE_LOCATION = "src/main/resources/courses.csv";
public final static String PREREQUISITE_FILE_LOCATION = "src/main/resources/prerequisites.csv";
This doesn't work. So I delete the .iml file, .idea and target folder from the project and reload them.
Read the correct path like this:
This would work then.

Java relative path in NetBeans

I am developing a NetBeans module where I have a Java package called testand another package called test.templates. I want to read a text file which is in the test.templates package from a Java file in the test package. I tried in several ways, but it gives a FileNotFoundException exception:
BufferedReader br = new BufferedReader(new FileReader("templates/test.txt"));
BufferedReader br = new BufferedReader(new FileReader("/test/templates/test.txt"));
BufferedReader br = new BufferedReader(new FileReader("src/test/templates/test.txt"));
But none of these worked.. I want to use the relative path, not the absolute path. What should I do?
You will want to use getResource or getResourceAsStream.
Example on java2s.com:
http://www.java2s.com/Code/Java/Development-Class/Loadresourcefilerelativetotheclasslocation.htm
You should note somethings about relative path (Netbeans):
+ File: Default is project folder, means outside of src folder.
If you save to test.txt, it will generate: project/test.txt.
If you save to data/test.txt, ... project/data/test.txt
So if you want to load file, you just do it conversely. Like this, you should put your files in project/data/filename.txt. Then when code, you get path: data/filename.txt.
+ ImageIcon: I will share later if can.
+ Image(SplashScreen): I will share later.
getResource() returns a URL, so to extract the filename, you can try calling getFile().
The filepath you pass to getResource will be based on your netbeans package. Use a leading slash to denote the root of the classpath.
Example:
getResource(/db_files/table.csv).getFile()
try
{
BufferedReader br = new BufferedReader(new FileReader(getClass().getResource("/test/templates/test.txt").toString().substring(6)));
}
catch(Exception ee)
{
JOptionPane.showMessageDialog(this, ee);
}

Categories

Resources