BuferredReader problems - java

I am having trouble reading from a file. Here is my code can anyone show me where I am wrong?
public static Map<Route, List<Service>> read(String fileName)
throws IOException, FormatException {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String strLine;
while((strLine = reader.readLine())!= null)
{
/* Own Code */
}
reader.close();
}
I am having a FileNotFound Exception. May this be a the location of my file that is wrong?

You seem to want to use a resource. A resource is not accessed as a file, it is better to use it as a stream.
InputStream resourceStream = MyClass.class.getResourceAsStream(fileName);
BufferedReader myReader = new BufferedReader(new InputStreamReader(resourceStream));
Above code takes the location of your class in account, so you can simply use the fileName as is, without a path, and place the fileName next to your .java file. It will automatically be placed next to the generated .class files and - when packaged - in your .jar file.

Just as owlstead commented keep in appropriate location and try like this
URL url = ClassLoader.getSystemResource(fileName);
br = new BufferedReader(new InputStreamReader(url.openStream()));
i.e keep the file in classes folder or bundle with jar or current working directory etc.

Related

Reading a resource file from either a "regular" file or a jarred file

We're developing a webapp and we have some files to read from a resources directory. During preliminary development and testing, we'd like to be able to read directly from the file in the resources directory. On the other hand, we want to read the resource file from a jar file when the webapp is deployed.
I've read other questions that indicate how to read files from jars. The essence of the idea is to get a BufferedReader and to read from that.
I've written the following code that allows me to create a BufferedReader from either the file system or a jar file, passing in the file name, e.g. myResource.txt, and the ClassLoader, e.g. getClass().getClassLoader(). It seems like it could be made better and/or simpler. Please help.
public static BufferedReader getBufferedReader(String fileToFind,
ClassLoader classLoader) {
BufferedReader bufferedReader = null;
// Try to find file in file system
final URL resource =
classLoader.getResource(fileToFind);
if (resource != null) {
String fileName = resource.getFile();
if (fileName != null) {
try {
final FileReader fileReader = new FileReader(fileName);
bufferedReader = new BufferedReader(fileReader);
}
catch (FileNotFoundException e) {} // no problem, move on
}
}
if (bufferedReader == null) {
// Try to find file in jar file
InputStream inputStream =
classLoader.getResourceAsStream(fileToFind);
final InputStreamReader streamReader = new InputStreamReader(inputStream);
bufferedReader = new BufferedReader(streamReader);
}
return bufferedReader;
}
Rather than trying to address the resource as a File just ask the ClassLoader to return an InputStream for the resource instead via getResourceAsStream:
InputStream in = getClass().getResourceAsStream("/file.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
As long as the file.txt resource is available on the classpath then this approach will work the same way regardless of whether the file.txt resource is in a classes/ directory or inside a jar.
One cannot turn a resource "file" inside a jar into a File. Only when classpath is immediately on classes, such as an unpacked war file. Such a resource has an URL like file:jar:/.../xxx.jar!.../yyy.txt
However, one could use Path & a file system view to copy a Path from a resource.
In your code it suffices to just use getResourceAsStream.
public static BufferedReader getBufferedReader(String fileToFind,
ClassLoader classLoader) {
InputStream inputStream = classLoader.getResourceAsStream(fileToFind);
InputStreamReader streamReader = new InputStreamReader(inputStream,
StandardCharsets.UTF_8);
return new BufferedReader(streamReader);
}
Mind fileToFind should not start with a / and should be an absolute path, when using a ClassLoader.
I specified the Charset, as you are taking the default, which would differ on a Linux production server, and a local Windows developer's machine.

Reading text file works in IDE but not in .jar

I am using
File file = new File("res/movies.txt");
to read text from a bundled .txt file. My code works perfectly when running the program within IntelliJ IDEA, but when I create a .jar file and run it, it gives a "File not found" error. What can I do to make the code work both in the IDE as well as in the jar file?
You need to load the file as a resource. You can use Class.getResourceAsStream or ClassLoader.getResourceAsStream; each will give return an InputStream for the resource.
Once you've got an InputStream, wrap it in an InputStreamReader (specifying the appropriate encoding) to read text from it.
If you need to sometimes read from an arbitrary file and sometimes read from a resource, it's probably best to use separate paths to either create a FileInputStream for the file or one of the methods above for a resource, then do everything else the same way after that.
Here's an example which prints each line from resources/names.txt which should be bundled in the same jar file as the code:
package example;
import java.io.*;
import java.nio.charset.*;
public class Test {
public static void main(String[] args) throws IOException {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(
Test.class.getResourceAsStream("/resources/names.txt"),
StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
}
}
try to change
File file = new File("res/movies.txt");
to
File file = new File("res/movies.jar");
this of course assumes the filename is movies.jar

Cannot find file in netbeans + glassfish project

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.

Java Reading textfile in Runnable JAR file ERROR

I have to make a project for school; it's a game. I load the map from a text file. Currently I do it with a scanner, but I can't manage to get it working in a Runnable JAR file without putting the res file next to the JAR file. I want to get the text file inside; it worked with BufferedImages, but the text file doesn't work. I have this code:
public String ReadTextFile(String path) throws IOException {
String HoldsText= null;
FileReader fr = new FileReader(getClass().getResource(path).toString());
BufferedReader br = new BufferedReader(fr);
while((HoldsText = br.readLine())!= null){
System.out.println(HoldsText);
}
return HoldsText;
}
path = "res/Maps/Map2.txt"
error:
java.lang.NullPointerException
at aMAZEing.TextManager.ReadTextFile(TextManager.java:22)
at aMAZEing.Map.openFile(Map.java:89)
at aMAZEing.Map.<init>(Map.java:31)
at aMAZEing.Board.<init>(Board.java:50)
at aMAZEing.Maze.<init>(Maze.java:24)
at aMAZEing.Maze.main(Maze.java:15)
file structure: http://speedcap.net/sharing/screen.php?id=files/a9/77/a977e8b487f21e67db941a96087561cd.png
This doesn't seem to work though. I've researched a lot but could not find anything that worked for me. I just need the whole text file in a string, the rest is easy with substring and so on.
EDIT!:
The resolution to this was that my path had res in it, and it didn't work because of that. I deleted the res and got "/Maps/Map2.txt" as path, now the file loads and my map is displayed again.
public static String ReadTextFile(String path) throws IOException{
String HoldsText= null;
InputStream is = getClass().getResourceAsStream(path);
InputStreamReader fr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(fr);
StringBuilder sb = new StringBuilder();
while((HoldsText = br.readLine())!= null){
sb.append(HoldsText)
.append("\n");
}
return sb.toString();
}
You need to append the lines and use InputStreamReader instead of FileReader

Main.class.getResource() and jTextArea

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)

Categories

Resources