I am developing a project with GWT and Netbeans. I have an RPC. I have put a text file in the server package "org.myname.server" and I want to read it with a server side method belonging to the class GWTServiceImpl. The text file and the file GWTServiceImpl.java are in the same package. The code is the following:
String text="";
try
{
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
String line;
while((line = br.readLine()) != null)
{
text=text+line;
System.out.println("here is the line: "+line);
}
br.close();
}
catch (Exception e) { }
return text;
It says that it can't access the file. I haven't included the entire path because the file is in the same folder of the method. So why doesn't it work?
File paths aren't relative to “classes”, but to the “current working directory”, so it'll depend how your server is launched, and will likely be different in development and production.
If the file is packaged as a resource in your webapp, then use the appropriate way of loading it: if it's in WEB-INF/classes or in a JAR in WEB-INF/lib, then use getClass().getResourceAsStream("file.txt"); otherwise use ServletRequest#getResourceAsStream().
Yes Thomas is right. So in order to create the buffered reader the code is the following:
InputStream is= getClass().getResourceAsStream(filepath);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
Related
I am working with eclipse and I try to read a HTML file to display it in a web browser (I am doing a http Java server).
I was using FileReader() function and it worked fine, then I restarted eclipse and it gave me the following error:
Exception in thread "main" java.io.FileNotFoundException: index.html
this is how I read the file :
String httpContent;
BufferedReader br = new BufferedReader(new FileReader("index.html"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append("\n");
line = br.readLine();
}
httpContent = sb.toString();
} finally {
br.close();
}
the file "index.html" is on the same level as the java file.
What should I change to get FileReader to work again?
So I don't know if closing eclips resets some parameters but to solve my problem, I just put the path to my HTML file from the project folder
so : src/Ex5/index.html instead of index.html
In my program I made a saving and loading system for text files. The Save function works perfectly as intended but the Load gives a NullPointerException.
Here's the load function
String path = "C:\\Levels\\File.txt";
LevelHandler.loadLevel(path);
Here's the loadLevel function
public static void loadLevel(String file){
String level = LevelLoader.loadFileAsString(file);
//other, unimportant, code
}
And here's the loadFileAsString function
public static String loadFileAsString(String file){
StringBuilder builder = new StringBuilder();
try {
InputStream in = LevelLoader.class.getResourceAsStream(file);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
String line;
while((line = bufferedReader.readLine()) != null){
builder.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
return builder.toString();
}
It's failing because it's looking for the file in the class folder regardless of what directory I pass in. How can I get the location of the .jar regardless of where the user places it on their computer?
you can get the .jar related location using ./
./ provides related path of your jar
The fix I came up with was to remove the InputStreamreader
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
This will be able to read files from any specified location on the computer, but still not from inside the jar. However it works perfectly fine with pretty much any other specified location.
Can anyone tell me how I can make a file recognised by my plug in project.
I have one pom. xml file in my project path like "AA/pom.xml" and I was able to copy this file and make a new one in another location.
But when I'm tying to do the same thing in my plug in project, I'm getting FileNotFoundException.
Below is the code which works in a simple java project but not in eclipse plug in project.
private void createPomFile(String location, String projectName, String string) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("\\pom.xml"), "UTF-8"));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(location + projectName + string), "UTF-8"));
String line = null;
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.write("\n");
}
// Close to unlock.
reader.close();
// Close to unlock and flush to disk.
writer.close();
}
StackTrace:
java.io.FileNotFoundException: \pom.xml (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at createservicestemplate.wizards.SampleNewWizard.createPomFile(SampleNewWizard.java:320)
at createservicestemplate.wizards.SampleNewWizard.doFinish(SampleNewWizard.java:288)
at createservicestemplate.wizards.SampleNewWizard.access$0(SampleNewWizard.java:118)
at createservicestemplate.wizards.SampleNewWizard$1.run(SampleNewWizard.java:86)
at org.eclipse.jface.operation.ModalContext$ModalContextThread.run(ModalContext.java:121)
You will have to remove the \\ in the argument of FileInputStream. So that the Java code searches for the the file directly under your project folder.
In your code, the java class searches for pom.xml right inside the directory where your workspace is placed.
For Example, if you have the workspace in "D:" drive, then upon executing your code with \\pom.xml in FileInputStream, then your code searches for presence of D:\\pom.xml. Hence pom.xml is present in your project as AA\\pom.xml, the exception is thrown.
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("pom.xml"), "UTF-8"));
UPDATE after the user need: For Eclipse Plugin
For eclipse plugin the below will work. Figured it out after your latest comment. I have checked the same in Eclipse plugin and it is working for me.
try {
String line = null;
FileInputStream fi = (FileInputStream) your_class_name.class.getResourceAsStream("/pom.xml");
BufferedReader bf = new BufferedReader(new InputStreamReader(fi));
while((line = bf.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This line
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("\\pom.xml"), "UTF-8"));
says: "Read a file called pom.xml in the root directory of the current disk drive" (that is what \ means).
Check what is your current directory and where is that pom file:
System.out.println(" Working directory is "+ new File("temp.txt").getCanonicalPath());
Here is the code but it does not delete storedIp file and rename tempFile to storedIP. Both file exist
String host=ipParsing(hostName);
File tempFile= new File("tempFile.txt");
File strFile = new File("StoredIp.txt");
BufferedReader bufferReader = new BufferedReader( new FileReader(strFile));
BufferedWriter bw = new BufferedWriter(new FileWriter(tempFile));
String line;
while ((line = bufferReader.readLine()) != null) {
if(host.equals(line))
{
found=true;
line="";
}
bw.write(line);
if(!line.equals(""))
bw.newLine();
}
bw.close();
bufferReader.close();
strFile.delete();
tempFile.renameTo(new File ("StoredIP.txt"));
Well, a call to File.delete() does not necessary delete the file.
As the JavaDoc says: be sure to check the return value.
Ignoring this (like you did) is a common source of errors.
One occasion where this delete/renameTo easily goes awry, is when the files are in use. A solution seen consists of using an additional lock file. Too complicated for such a simple thing.
Using an embedded database, like java's own Derby, which is not that difficult. The database needs no extra provision. There are good tutorials with simple example code.
InputStream input = Faculty.class.getClassLoader().getResourceAsStream("Resources\\Names.txt");
DataInputStream in = new DataInputStream(input);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null && !strLine.equals("")) {
keywords.add(strLine);
}
The code above works in NetBeans. But when I packed the code into an executable Jar and ran it from command line, it gave me a NullPointerException because of the non-initialized input. So I suspect the Jar was not able to read the resource file packaged in it. The folder Resources is directly under source folder of my project. Can anyone give some hint what to try?
you should write like this:
getResourceAsStream("/Resources/Names.txt");
if you don't add the prefix '/', it means that your path is based on your class path, not the root path