Reading a text file in war archive [duplicate] - java

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

Related

How can I modify a text file inside a Jar file while runtime? [duplicate]

This question already has answers here:
Modifying a file inside a jar
(14 answers)
Closed 7 years ago.
Well as the question says, How is that possible?
This file is my proyect structure (I'm using eclipse).
When exported as Jar, I can access and print the "root.ini" content through console with the code below but, How can I write to that file while runtime?
This method is called from 'Main.java'
private void readRoot(){
InputStream is = getClass().getResourceAsStream("/img/root.ini");
BufferedReader br = null;
br = new BufferedReader(new InputStreamReader(is));
String path = "";
try {
path = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(path);
}
What I'm actually trying to do is get some text from a JTextField, and save it to "root.ini" file.
So when I try to write to that file like this
private void writeRoot() {
URL u = getClass().getResource("/img/root.ini");
File f = null;
try {
f = new File(u.toURI());
FileWriter fw = new FileWriter(f.getAbsolutePath());
BufferedWriter bw = new BufferedWriter(fw);
bw.write("Sample text"); //This String is obtained from a TextField.getText();
bw.close();
fw.close();
} catch (URISyntaxException | IOException e) {
e.printStackTrace();
}
}
And throws me this error
C:\Users\Francisco\Desktop\tds>java -jar TDS.jar
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: URI is not hierarchical
at java.io.File.(Unknown Source)
at main.Configuracion.writeRoot(Configuracion.java:99)
at main.Configuracion.access$1(Configuracion.java:95)
You can't change any content of a jar which is currently used by a jvm. This file is considered locked by the operating system and therefore can't be changed.
I suggest to write this file outside your jar file. e.g. in a /conf directory relative to the current working dir.

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) BufferedReader returning null when reading a file that isn't empty

Each file has one line with one letter. Why are both are returning null?
File saveFile = new File("saved.txt");
File pocFile = new File("playerOrComputer.txt");
if (!pocFile.exists()) {
pocFile.createNewFile();
}
if (!saveFile.exists()) {
saveFile.createNewFile();
}
BufferedReader brPoC = new BufferedReader(new FileReader(pocFile));
BufferedReader brSave = new BufferedReader(new FileReader(saveFile));
String savedChar = brSave.readLine();
brSave.close();
String playerOrComputerChar = brPoC.readLine();
brPoC.close();
System.out.println(savedChar);
System.out.println(playerOrComputerChar);
Try the while loop while reading using BufferedReader:
while ((savedChar = brSave.readLine()) != null) {
System.out.println(savedChar);
}
If your files Contains text it will definitely show:
Do not also leave the BufferedReader Open. Once you are done reading Close it:
if (brSave != null)br.close();
I suspect the below lines.
if (!pocFile.exists()) {
pocFile.createNewFile();
}
if (!saveFile.exists()) {
saveFile.createNewFile();
}
you have checked if not exists you are creating new file. I think it creates a new file.
Try giving complete location path of file File saveFile = new File("C:\\testing.txt");
And you can do this
if (!saveFile.exists()) {
System.out.println("File doesn't exits! Creating new file..");
saveFile.createNewFile();
}
Either try with the absolute path or if you are considering these files as part of your application, I mean if put in source folder, then you may use:
BufferedReader brPoC = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("saved.txt"));
BufferedReader brSave = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("playerOrComputer.txt"));
try giving the absolute path in the File constructor and in the absolute path replace \ by \\ in order to get rid of the escape sequence
Why are both are returning null?
With respect to you,both files contain some data.The IDE not able to find the files from location.
try getAbsolutePath() will return the exact path of your file.
saveFile.getAbsolutePath();
Its always better to null check while using readLine()

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)

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

Categories

Resources