Unable to read the file in Eclipse - java

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

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

How can I write code to access a text file when my class and the text file are in an Executable JAR?

I know this question has been asked many, many times before, but the answers don't seem to help me. Here is my specific issue:
I have a class "TaQL" that accesses two text files from within its void main(String args[]) method. The two text files are in the same package as this class: package "taql". The following code runs fine within Eclipse (Mars) IDE:
String stoplist = TaQL.class.getResource(stoplist).toURI().getPath();
String input = TaQL.class.getResource(input).toURI().getPath();
When I output these two strings I get the correct path to the resource and the code hums along.
However, when I use this method after packaging everything up in a JAR, both strings return "null".
Here is what my code does with each of these text files in the non-JAR version
Get filename string for each text file.
create a new File object from one string and a new FileReader object from the other.
These are fed into a stoplist function and a data input iterator, respectively.
What I really need to be able to do is to seamlessly access these two text files once they are all in a JAR and then use some reference to these to create a File and FileReader object.
Here is some diagnostic code I put in my main method. It will show what the JAR file is seeing as far as files (note that both input and stoplist are filename strings):
System.out.println("intput argument" + input);
System.out.println("Resource path"+TaQL.class.getResource(stoplist));
stoplist = TaQL.class.getResource(stoplist).toURI().getPath();
input = TaQL.class.getResource(input).toURI().getPath();
System.out.println("Path"+stoplist);
System.out.println("Input path" + input);
command line output from running the JAR version of my program (note that this code works perfectly fine when I run from Eclipse)
To actually access the bytes of those files that may be in a jar file you need to use Class#getResourceAsStream(stopList). The URI will give you a path that cannot be used with File or FileInputStream. It's working in your IDE because the IDE has not yet packaged up the files, therefore the #getPath finds an actual file path.
So try this instead:
try (Reader inputReader =
new InputStreamReader(
TaQL.class.getResourceAsStream(input))) {
BufferedReader in = new BufferedReader(inputReader);
for (String line; (line = in.readLine()) != null;) {
// do something with the line
}
}

java file relative path in eclipse

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.

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.

Categories

Resources