I have created a java project in eclipse and added certain text files like follows
FileReader fin=null;
BufferedReader bin=null;
fin=new FileReader("src/main/resources/League.txt");
bin=new BufferedReader(fin);
But after creation of the ruunable jar or just simple jar when I run the jar file it is showing that no text file is found or the path is not found. But I have added the text files in the main.resource of my project. How to handle it?
Use URLClassLoader.getSystemResourceAsStream, this works in jars and in eclipse...
Make sure there's a file in the latest Java version directory src\main\resources\League.txt. For example, say for Windows, C:\Program Files\Java\jdk1.7.0_25\src\main\resources\League.txt.
You need to give front slashes, not back ones. Also, this should be the code:
FileReader fin=null;
BufferedReader bin=null;
fin=new FileReader("src\\main\\resources\\League.txt"); // Because of Unicode restrictions.
bin=new BufferedReader(fin);
Maybe you check this as well: How to get a path to a resource in a Java JAR file
Try this. Even though the file is in src/resources you need not say src folder in path.
BufferedReader br = null;
try {
String sCurrentLine;
URL url = ClassLoader.getSystemResource("resources/League.txt");
br = new BufferedReader(new InputStreamReader(url.openStream()));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
Related
i wrote a program, but when my friends try to execute it it throw filenotfound exception, but the file is exist, here is my code, and in the folder have lib folder, the jar file and the "csv fajlok" and in the csv fajlok folder there is the 2 csv file
String csvFile = "csv fajlok\\pontcsoport.csv";
BufferedReader br = null;
String line = "";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
String[] pontGroupLine = line.split(";");
String[] price_split = pontGroupLine[1].split(" ");
try{
doubleDTList.add(Double.parseDouble(price_split[0]));
}catch(NumberFormatException e){
}
}
}catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(null, "Nem található a pontcsoport fájl (/csv fajlok)");
}catch (IOException e) {
}finally {
if (br != null) {
try {
br.close();
}catch (IOException e) {
}
}
}
If the file is outside the jar file, you should put an absolute path, or the "csv fajlok" folder should be in the same folder where you execute the jar file.
If the file is inside the jar file, you cannot access to it as a file but as a Stream, with the method Class.getResourceAsStream(String path).
Better to use Java NIO2 to read the file content:
List<String> lines = Files.readAllLines(Paths.get("path-to-file"), charset);
It's allow to avoid using while loop with redundant readers.
What is the OS installed on failed notebooks?
Also try to change folder name using '_' instead of space. I think it's the main reason of the issue.
There are many similar questions to this but this is not a duplicate. This is similar to "Can't access files in Jar file" but there is a slight difference. With a lot of experimentation and forum reading, I managed to access the contents of a file and display them from within the Jar file. The problem is that if I were to put the file inside a folder then my program would no longer work even though it works when I run the class file. This is a problem because when I make games and other programs I like having different folders for organisation like "maps" and "spritesheets". I made an experimental program to route out the problem and here is the code for it:
try {
InputStream is = getClass().getResourceAsStream("folder\\test.txt");
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
isr.close();
is.close();
} catch (Exception ex) {}
I didn't do anything in the catch section because I had already used it to find the area with the problem. Here is my directory structure:
JarFileText
classes
com
sayedhajaj
folder
test.txt
JarFileText.class
test.txt
source
com
sayedhajaj
JarFileText.java
When I try to access the copy of the text file that is not in the folder, everything works fine. However, if I try to access the copy in "folder", null is returned.
This is the solution:
try {
InputStream is = getClass().getResourceAsStream("folder/test.txt");
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
isr.close();
is.close();
} catch (Exception ex) {}
Here it is my folder project
I would like to read the file book-form.html which is in the directory web of my project and put it in a String.
This is how I call my function 'getFileContent':
String content = getFileContent("web/book-form.html");
And this is the function:
public String getFileContent(String filePath){
String line, content = new String();
try {
File file = new File(filePath);
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
while((line = br.readLine()) != null){
content += line;
}
br.close();
fr.close();
} catch(IOException e){
System.out.println(e.getMessage());
}
return content;
}
My problem is that netbeans tell me that it cannot find my file book-form.html
Any ideas ?
File path to resource in our war/WEB-INF folder?
Also you should close stream in a final block or use try-with-resource if you use jdk 7+
I find the way to do it:
Basically the program is in the main folder of Glassfish, so it's needed to put the entire path of your file from the root of your system to allow the program to find your file.
When I read a file from the jar file and want to put it in in a jTextArea, it shows me crypted symbols, not the true content.
What I am doing:
public File loadReadme() {
URL url = Main.class.getResource("/readme.txt");
File file = null;
try {
JarURLConnection connection = (JarURLConnection) url
.openConnection();
file = new File(connection.getJarFileURL().toURI());
if (file.exists()) {
this.readme = file;
System.out.println("all ok!");
}
} catch (Exception e) {
System.out.println("not ok");
}
return file;
}
And then i read the file:
public ArrayList<String> readFileToArray(File file) {
ArrayList<String> array = new ArrayList<String>();
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(file));
while ((sCurrentLine = br.readLine()) != null) {
String test = sCurrentLine;
array.add(test);
}
} catch (IOException e) {
System.out.println("not diese!");
} finally {
try {
if (br != null)
br.close();
} catch (IOException ex) {
}
}
return array;
}
Now, i put all lines from the ArrayList in the jTextArea, that showes me things like that:
PK����?����^��S?��3��� z_��
%�Q Tl?7��+�;�
�fK� �N��:k�����]�Xk,������U"�����q��\����%�Q#4x�|[���o� S{��:�aG�*s g�'.}���n�X����5��q���hpu�H���W�9���h2��Q����#���#7(�#����F!��~��?����j�?\xA�/�Rr.�v�l�PK�bv�=
The textfiled contains:
SELECTION:
----------
By clicking the CTRL Key and the left mouse button you go in the selection mode.
Now, by moving the mouse, you paint a rectangle on the map.
DOWNLOAD:
---------
By clicking on the download button, you start the download.
The default location for the tiles to download is: <your home>
I am sure that the file exists!
Does anyone know what the problem is? Is my "getResource" correct?
Based on the output, I'm suspecting your code actually reads the JAR file itself (since it starts with PK). Why not use the following code to read the text file:
Main.class.getResourceAsStream("/readme.txt")
That would give you an InputStream to the text file without doing the hassle of opening the JAR file, etc.
You can then pass the InputStream object to the readFileToArray method (instead of the File object) and use
br = new BufferedReader(new InputStreamReader(inputStream));
The rest of your code should not need any change.
This seems to be an encoding problem. FileReader doesn't allow you to specify that. Try using
br = new BufferedReader(new InputStreamReader(new FileInputStream(file), yourEncoding));
You seem to be making far too much work for yourself here. You start by calling getResource, which gives you a URL to the readme.txt entry inside your JAR file, but then you take that URL, determine the JAR file that it is pointing inside, then open that JAR file with a FileInputStream and read the whole JAR file.
You can instead simply call .openStream() on the original URL that getResource returned, and this will give you an InputStream from which you can read the content of readme.txt
br = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
(if readme.txt is not encoded in UTF-8 then change that parameter as appropriate)
This question already has answers here:
Where to place and how to read configuration resource files in servlet based application?
(6 answers)
Closed 5 years ago.
I am trying to read a text file from my war archive and display the contents in a facelets page at runtime. My folder structure is as follows
+war archive > +resources > +email > +file.txt
I try to read the file in the resources/email/file.txt folder using the following code
File file = new File("/resources/email/file.txt");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
StringBuffer buffer = new StringBuffer();
if (reader != null) {
String line = reader.readLine();
while (line != null) {
buffer.append(line);
line = reader.readLine();
// other lines of code
The problem however is that when I the method with the above code runs, A FileNotFoundException is thrown. I have also tried using the following line of code to get the file, but has not been successful
File file = new File(FacesContext.getCurrentInstance()
.getExternalContext().getRequestContextPath() + "/resources/email/file.txt");
I still get the FileNotFoundException. How is this caused and how can I solve it?
Try below:
InputStream inputStream =
getClass().getClassLoader().getResourceAsStream("/resources/email/file.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream ));
Try to avoid the File, as this is for reading things from the file system.
As your resource is bundled into the WAR, you can access it via the classloader.
Ensure that the resource is bundled into your WEB-INF/classes folder.
InputStream in =
new InputStreamReader(FileLoader.class.getClassLoader().getResourceAsStream("/resources/email/file.txt") );
This is a good blog on the topic
http://haveacafe.wordpress.com/2008/10/19/how-to-read-a-file-from-jar-and-war-files-java-and-webapp-archive/
If you want to get the java File object, you can try this:
String path = Thread.currentThread().getContextClassLoader().getResource("language/file.xml").getPath();
File f = new File(path);
System.out.println(f.getAbsolutePath());
I prefer this approach:
InputStream inputStream = getClass().getResourceAsStream("/resources/email/file.txt");
if (inputStream != null) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
...
} catch ...
} else ...
Three reasons:
it supports both: loading resources from an absolute path and from a relative path (starting from the given class) -- see also this answer
the way to obtain the stream is one step shorter
it utilizes the try-with-resources statement to implicitly close the underlying input stream