Main.class.getResource() and jTextArea - java

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)

Related

How to handle FileNotFoundException using try and catch block in Java?

I have written a program in which I am reading a file through the BufferedReader. which file I am reading it may be in .txt format or .csv format.
I want in if file is not available with .txt extension BufferedReader read it with
.csv extension.
I have created a String "FileName" and storing file path on it. and in path variable i have stored file location.
path = "C:\Users\Desktop\folder(1)\"
and I am trying try catch block as follow.
try
{
FileName = path+"abc.txt";
}
catch(Exception e)
{
FileName = path+"abc.csv";
}
BufferedReader BR = new BufferedReader(new FileReader(FileName));
But I am getting java.io.FileNotFoundException.
The exception is thrown in the line BufferedReader SoftwareBundle = new BufferedReader(new FileReader(FileName));
So you need the try/catch-block arround this line:
try
{
FileName = path+"abc.txt";
BufferedReader SoftwareBundle = new BufferedReader(new FileReader(FileName));
}
catch(Exception e)
{
FileName = path+"abc.csv";
BufferedReader SoftwareBundle = new BufferedReader(new FileReader(FileName));
}
This is the ideal structure for the code:
String filename = null;
try (BufferedReader bundle = null) {
try {
filename = path + "abc.txt";
bundle = new BufferedReader(new FileReader(filename));
} catch(FileNotFoundException e) {
filename = path + "abc.csv";
bundle = new BufferedReader(new FileReader(FileName));
}
// use 'bundle' here
} catch(FileNotFoundException e) {
// log that >>neither<< file could be opened.
}
Notes:
Don't catch Exception. If you do that, you will catch all sorts of unexpected stuff, in addition to the exceptions that you are anticipating.
Use a "try with resource" to ensure that that the reader that was opened is always closed.
You need to get the scoping right ... unless you are prepared to duplicate the code that uses the reader.
Even with the "try again" logic, you still need to deal with the case where all of the filenames that you try fail. AND you need to make sure that the "all fail" case doesn't attempt to use the reader.

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.

Unable to add text file in java eclipse during creation of jar

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();
}
}

Java project can't find file

I have a project that finds a text file and makes it into an array of characters. However, for some reason or another it isn't finding the file. This is all the code involving opening/reading the file:
public void initialize(){
try{
File file = new File(getClass().getResource("/worlds/world1.txt").toString());
BufferedReader reader = new BufferedReader(
new InputStreamReader(
new FileInputStream(file),
Charset.forName("UTF-8")));
int c;
for(int i = 0; (c = reader.read()) != -1; i ++) {
for(int x = 0; x < 20; x++){
worlds[1][x][i] = (char) c;
c = reader.read();
}
}
}catch(IOException e){
e.printStackTrace();
}
}
When ran, it shows in the console that it is pointing to the correct file, but claims nothing exists there. I've checked, and the file is completely intact and in existence. What could be going wrong here?
You should not get a resource like that. You can use
BufferedReader reader = new BufferedReader(new InputStreamReader(
getClass().getResourceAsStream("/worlds/world1.txt")
));
Also, be careful when you package your application if you develop it inside an IDE, otherwise you'll run into common CLASSPATH troubles
File path for embedded resources is calculated from the package root folder. Assuming that src folder is the root package folder, make sure, that world1.txt file is located at src/worlds/ folder and full path is src/worlds/world1.txt
Second point, use the following code to obtain embedded file reader object:
// we do not need this line anymore
// File file = new File(getClass().getResource("/worlds/world1.txt").toString());
// use this approach
BufferedReader reader = new BufferedReader(
new InputStreamReader(
getClass().getResourceAsStream("/worlds/world1.txt"),
Charset.forName("UTF-8")));
You haven't indicated where your file lives.
getClass().getResource is used to locate a resource/file on your classpath; the resource may be packaged in your jar, for example. In this case, you can't open it as a File; see Raffaele's response.
If you want to locate the resource/file on the file system, then create the File object directly without getResource():
new File("/worlds/world1.txt")
I was using Netbeans and I was getting similar results. When I defined the file Path from the C drive and ran my code it stated: Access has been denied.
The following code ran fine, just back track your file location to the source (src) file.
//EXAMPLE FILE PATH
String filePath = "src\\solitaire\\key.data";
try {
BufferedReader lineReader = new BufferedReader(new FileReader(filePath));
String lineText = null;
while ((lineText = lineReader.readLine()) != null) {
hand.add(lineText);
System.out.println(lineText); // Test print of the lines
}
lineReader.close(); // Closes the bufferReader
System.out.print(hand); // Test print of the Array list
} catch(IOException ex) {
System.out.println(ex);
}

Reading a line of a txt file in assets

I have a text file placed in assets and I want to read one line of it at a time. My problem is that I do not know how to access the file in Activity, and then once I access it, how would I go about only selecting one line?
If keeping the txt file in assets is a bad idea, where should I put it for easier access?
I really appreciate any help!
This is a snippet I use to prepopulate tables in my RSS feed reader. You can use it as a track for your needs.
In res/raw/ I have file feeds.txt. The file is referenced is code like R.raw.feeds.
final Resources resources = mHelperContext.getResources();
InputStream inputStream = resources.openRawResource(R.raw.feeds);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream), 8192);
try {
String line;
while ((line = reader.readLine()) != null) {
//make the use you want with "line"
}
} catch (IOException e) {
Log.e(TAG, "Error loading sample feeds.");
throw new RuntimeException(e);
}
To open assests, you'll need to call
<context>.getAssets().open(<your file>);
<context> is your activity, so if this is in your onCreate, then it would be this. That call returns an inputstream, which you can then handle however you please.
I don't see how it would be a particularly bad idea to keep your text file there, depends on what you're using that text file for.
Try this:
Make a new method for example readMyFile().
It must looks like this:
private String readMyFile(File file) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(file));
StringBuilder txt = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
txt.append(line);
txt.append("\n");
}
reader.close();
return txt.toString();
Paste it to your code, and use the method (readMyFile([the file what you want to read in assets]).
Hope it helps.

Categories

Resources