Cannot find file in netbeans + glassfish project - java

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.

Related

How do I read all the contents of a HTML file inside of my jar and store it in a string

I have an HTML file under a directory in my JAR file under pages/newTab.html, and in Eclipse it obviously is in res/pages/newTab.html. My goal here is to read the contents of the whole HTML file and store it in a String.
I have tried multiple ways to get the file as a resource, then read it with a BufferedReader, it works in Eclipse, but not in the Runnable JAR. This is normally how I get the file as a resource, this works in Eclipse, but not in the Runnable JAR.
getClass().getResource("/pages/" + url.substring(7))
Here is what I have so far.
File file = new File(getClass().getResource("/pages/" + url.substring(7)).toURI());
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
stringBuffer.append("\n");
}
fileReader.close();
jep.setContentType("text/html");
jep.setText(stringBuffer.toString());
jep is the JEditorPane we are printing the text to.
EDIT: I do get an java.lang.IllegalArgumentException: URI is not hierarchical when Running the Runnable JAR with File file = new File(getClass().getResource("/pages/" + url.substring(7)).toURI());
Save the html outside the jar, this is what you can do with configuration files and other stuff like that. Create a folder for the application and store the executable jar and html inside.
- application\
------- executable.jar
------- htmlFile.html
now do something like this:
try {
List<String> lines = new ArrayList<>(Files.readAllLines(Paths.get("htmlFile.html"))));
String content = "";
for (String line : lines) {
content += line + "\n";
}
jep.setContentType("text/html");
jep.setText(content);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Reading files from outside the class path in Intellij

I am trying to read a file given its path that may not be inside the class path of the current project; the project has been exported as a separate .jar file and should be run from any directory it is located in. The code for reading the file is:
try {
FileInputStream fstream = new FileInputStream(inputFile);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fstream));
String strLine;
while ((strLine = bufferedReader.readLine()) != null) {
// read file
bufferedReader.close();
} catch (IOException e) {
System.out.println("Err couldn't find " + inputMailFile);
}
This question only refers to the case when a file is being read from the current working directory.
How can I read a file given only its path?
inputFile is a string to the file path. For example:
C:\\Users\\user\\file.txt

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

Reading a text file in war archive [duplicate]

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

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