FileNotFoundException with getResources - java

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.

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

BufferedReader/FileReader is not finding path correctly even with try/catch

I am trying to read from a text file using BufferedReader and FileReader and I am constantly running into this problem:
java.io.FileNotFoundException: dicomTagList.txt (The system cannot find the file specified)C:\temp\workspace\DICOMVALIDATE\dicomTagList.txt
I can't seem to find out why this is occurring when I have that file in the correct directory and was able to even verify it with getAbsolutePath() Method in FileReader.
Can anyone advise why this may be?
Here is my code snippet:
public void readFromTextFile(File path) throws IOException
{
try
{
System.out.println(dicomList.getAbsolutePath());
String line;
BufferedReader bReader = new BufferedReader(new FileReader(dicomList));
while( (line = bReader.readLine()) != null)
{
System.out.println(line);
}
bReader.close();
}
catch(FileNotFoundException e)
{
System.err.print(e);
}
catch(IOException i)
{
System.err.print(i);
}
}
Are you sure that the file really exists? What will the following expression print:
dicomList.exists();
In Java java.io.File is representing just a path to a file, not necessarily a real file. This means you can create File object even if the underlying path does not exist.

Unable to open file in JAVA

I am trying to open a file in JAVA using BufferedReader but it cannot open the file. Here is my code
public static void main(String[] args) {
try
{
BufferedReader reader = new BufferedReader(new FileReader("test.txt"));
String line = null;
while ((reader.readLine()!= null))
{
line = reader.readLine();
System.out.println(line);
}
reader.close();
}
catch(Exception ex)
{
System.out.println("Unable to open file ");
}
}
It goes to the exception and prints Unable to open file. Any suggestions why I cannot able to read it.
If you want to be more nearly modern, try the Java 7 solution, taken from the Paths Javadoc:
final Path path = FileSystems.getDefault().getPath("test.txt"); // working directory
try (final Reader r = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
String line = null;
while ((line = r.readLine()) != null) {
System.out.println(line);
}
} // No need for catch; let IOExceptions bubble up.
// No need for finally; try-with-resources auto-closes.
You'll need to declare main as throwing IOException, but that's okay. You have no coherent way of handling IOException anyway. Just read the stack trace if an exception is triggered.
I don't know why this happened, but the problem seemed that I did not enter the complete path for the file even though the file was in the same folder. Ideally if the file is in the same folder then I wouldn't need to enter the entire pathname.
Try doing a check if it exists first:
File file = new File("test.txt");
if (!file.exists()) {
System.err.println(file.getName() + " not found. Full path: " + file.getAbsolutePath());
/* Handling code, or */
return;
}
BufferedReader reader = new BufferedReader(new FileReader(file));
/* other code... */

Categories