InputStream from getResourceAsStream results in NULL - java

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

Related

bufferedReader only read local csv file

I'm new to Java and I'm trying to use this class to return the content of "test.csv".This only works when I use the path of local files.
public class CSVtoArray2 {
public static final String filename = "C:\\eclipse\\workspace\\project\\src\\main\\webapp\\resources\\csv\\test.csv";
public String testMethod() throws IOException {
BufferedReader wr = null;
try {
wr = new BufferedReader(new FileReader(new File(filename)));
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = wr.readLine()) != null) {
stringBuffer.append(line);
stringBuffer.append("\n");
}
wr.close();
return stringBuffer.toString();
} finally {
wr.close();
}
}
}
When I change
"C:\eclipse\workspace\project\src\main\webapp\resources\csv\test
.csv"
to "/resources/csv/test.csv",
this class gets a null return.
Anyone here who can help?
Thanks!
UPDATE:
Solution:
Copying my CSV file to project resources folder:
ClassLoader classLoader = getClass().getClassLoader();
File filename = new File(classLoader.getResource("csv/test.csv").getFile());
org.apache.commons.io.IOUtils.toString(CSVtoArray2.class.getResourceAsStream("/csv/test.csv"), Charset.forName("UTF-8")))
It is tricky, what is root path for the resource. In Eclipse you can mark some folder (e.g. webapp/recource) as resource folder. And When you build jar file, resource folder content will be in the root. So if you start your resource path from /, it means root of jar (i.e. root of resource folder).
I do not use relative paths, so you could look at open resource with relative path in java to get more info about it.

java find the location of a .jar regardless of where user puts it

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.

I can't read a text file in GWT

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

FileNotFoundException in eclipse Plugin project

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

FileNotFoundException with getResources

I used Class.getResource (String) to retrieve the url of a file, and it works very well, but when I try to 'insatncié a FileReader with the url returned, an exception:java.io.FileNotFoundException is triggered
URL bpmnResourceUrl = ConvertXmlToJson.class.getClassLoader().getResource("file.txt");
Reader reader = new FileReader(bpmnResourceUrl.toString());
A Resource in Java is not a File. If the Resource is inside a JAR, for example, you can't access it like a File. You have to explode the JAR first. You may try:
Class.getResourceAsStream()
to read the content. Here is a short example:
public class Example {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(Example.class.getResourceAsStream("/META-INF/MANIFEST.MF")));
String line;
do {
line = br.readLine();
if (line != null) System.out.println(line);
} while (line != null);
}
}
Don't open it as a file, use it as InputStream, in your case, if you want a Reader to get the data then you can use:
InputStream is = ConvertXmlToJson.class.getClassLoader().getResourceAsStream("file.txt");
Reader reader = new InputStreamReader(is);
When you load a resource from Classpath, such resource can be located inside a jar file, so It's not accesible like a regular file in filesystem, but you can open a Stream to read it, as the code shows.

Categories