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) {}
Related
I have a VBS file xxx.vbs that i'm able to execute it on my local machine using the below code:
String cmd = "wscript filePath\\xxx.vbs";
Process p = Runtime.getRuntime().exec(cmd);
But when i create a war file of the project and deploy it on the server, I'm not able to execute the vbs file.
I can however execute the VBS file manually on the server. So there is nothing wrong with the VBS file.
Any idea on what may be the reason for the above?
Try adding the below snippet to determine whats happening in the background.
String line="";
try
{
InputStreamReader isr = process.getInputStream();
BufferedReader br = new BufferedReader(isr,4094);
while ( (line = br.readLine()) != null)
System.out.println(line);
} catch (IOException ioe)
{
ioe.printStackTrace();
}
try
{
isr = process.getErrorStream();
br = new BufferedReader(isr,4094);
while ( (line = br.readLine()) != null)
System.out.println(line);
} catch (IOException ioe)
{
ioe.printStackTrace();
}
P.S. The above snippet is just for informational purpose.
Runtime.getRuntime().exec() will simply begin the execution, and exits..
Trying the above will eventually show you the exceptions, if any, and the output of the script file you are trying to run.
However, the better way is to create a seperate runnable which can accept the input stream and display its content instead of writing the code I specified above.
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();
}
}
I've been trying to read a file for the last few days and have tried following other answers but have not succeeded. This is the code I currently have to import the text file:
public ArrayList<String> crteDict() {
try {
BufferedReader br = new BufferedReader
(new FileReader("/program/res/raw/levels.txt"));
String line;
while ((line = br.readLine()) != null) {
String[] linewrds = line.split(" ");
words.add(linewrds[0].toLowerCase());
// process the line.
}
br.close();
}
catch (FileNotFoundException fe){
fe.printStackTrace();
It is meant to read the text file and just create a long Array of words. It keeps ending up in the FileNotFoundException.
Please let me know any answers.
Thanks!
IF your file is stored in the res/raw folder of the android project, you can read it as follows, this code must be inside an Activity class, as this.getResources() refers to Context.getResources():
// The InputStream opens the resourceId and sends it to the buffer
InputStream is = this.getResources().openRawResource(R.raw.levels);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String readLine = null;
try {
// While the BufferedReader readLine is not null
while ((readLine = br.readLine()) != null) {
Log.d("TEXT", readLine);
}
// Close the InputStream and BufferedReader
is.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
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)
I have folders in a repository in SVN which have an en-dash ("\u2013") in their names.
I am first calling the "svn list" (in my Windows 7 + UTF-8 encoding) to get the list of the directory.
After that calling BufferedReader readLine(), it reads the text of the list.
The name of the folders being displayed contain a hyphen ("\u002D") instead of the en-dash ("\u2013").
Are there any limitations regarding that ?
class Test {
public static void main(String args[]) {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\test–ing.xml"));
System.out.println(br.readLine());
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();
}
}
} // end main
This is probably the problem:
br = new BufferedReader(new FileReader("C:\\test–ing.xml"));
That will use the platform default encoding. You've said that the file is UTF-8-encoded - so you need to specify that you want UTF-8, which means avoiding FileReader's broken API:
br = new BufferedReader(new InputStreamReader(
new FileInputStream("C:\\test–ing.xml"), "UTF-8"));
That's assuming the file really is valid UTF-8 containing the expected character. You should check that before doing anything else.
Alternatively, given that this is XML, I assume in your real code you're going to use it as XML? If so, I would just load it straight from an input stream, and let the XML parser handle the encoding.