FileInputStream : No such file or directory [duplicate] - java

This question already has an answer here:
Java File does not exists but File.getAbsoluteFile() exists
(1 answer)
Closed 5 years ago.
It works well "new FileInputStream(f.getAbsoluteFile())"
private byte[] loadFile(String path) throws IOException {
File f = new File("./build/classes/" + path);
try (InputStream is = new FileInputStream(f.getAbsoluteFile())) {
byte[] data = loadFile(is);
return data;
}
}
And "new FileInputStream(f)"
private byte[] loadFile(String path) throws IOException {
File f = new File("./build/classes/" + path);
try (InputStream is = new FileInputStream(f)) {
byte[] data = loadFile(is);
return data;
}
}
throw exception:
java.io.FileNotFoundException: ./build/classes/traces/onmethod/ErrorDuration.class (No such file or directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
I can't imagine why.

First make sure you run your two programs from the same working directory.
Also, in the first case, your path is resolved to an absolute path first.
For example: /opt/local/myprod/bin/build/classes/traces/onmethod/ErrorDuration.class
Whle FileInputStream uses the 'simple path' of your file (File.getPath())
Depending on your current work directory, your permissions and your symbolic links those two paths can mean two different things.
From the directory you run your program - does this path work ?
ls ./build/classes/traces/onmethod/ErrorDuration.class
Also see:
What's the difference between getPath(), getAbsolutePath(), and getCanonicalPath() in Java?

Related

How do you create non-existing folders/subdirectories when copying a file with Java InputStream?

I have used InputStream to succesfully copy a file from one location to another:
public static void copy(File src, File dest) throws IOException {
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream("C:\\test.txt");
os = new FileOutputStream("C:\\javatest\\test.txt");
byte[] buf = new byte[1024];
int bytesRead;
while ((bytesRead = is.read(buf)) > 0) {
os.write(buf, 0, bytesRead);
}
} finally {
is.close();
os.close();
}
}
The problem appears when I add a non-existing folder into the path, for example:
os = new FileOutputStream("C:\\javatest\\javanewfolder\\test.txt");
This returns a NullPointerException error. How can I create all of the missing directories when executing the copy process through Output Stream?
First, if possible I'd recommend you to use the java.nio.file classes (e.g. Path), instead of the File based approach. You will create Path objects by using a file system. You may use the default filesystem, if no flexibility is needed here:
final String folder = ...
final String filename = ...
final FileSystem fs = FileSystems.getDefault();
final Path myFile fs.getPath(folder, filename);
Then your problem is easily solved by a very convenient API:
final Path destinationFolder = dest.getParent();
Files.createDirectories(myPath.getParent());
try (final OutputStream os = Files.newOutputStream(myFile)) {
...
}
The Files.createDirectories() method will not fail if the directory already exists, but it may fail due to other reasons. For example if a file "foo/bar" exists, Files.createDirectories("foo/bar/folder") will most likely not succeed. ;)
Please read the javadoc carefully!
To check, if a path points to an existing directory, just user:
Files.isDirectory(somePath);
If needed, you can convert between File and Path. You will lose file system information, though:
final Path path1 = file1.toPath();
final File file2 = path2.toFile();
You could use Files.createDirectories:
Files.createDirectories(Paths.get("C:\\javatest\\javanewfolder"));
Also, you could use Files.copy to copy file )

java.io.IOException java

We trying to get bytes from a file using below code.
getBytes("/home/1.ks");
Before that, we have make sure the file is exists.
public static void getBytes(final String resource) throws IOException {
File file = new File(resource);
if (file.exists()) {
System.out.println("exists");
} else {
System.out.println("not exists");
}
final InputStream input = APIController.class.getResourceAsStream(resource);
if (input == null) {
throw new IOException(resource);
} else {
System.out.println("Not null");
}
}
Here the output and exceptions
exists
java.io.IOException: /home/1.ks
at com.example.demo.controller.APIController.getBytes(APIController.java:164)
at com.example.demo.controller.APIController.transactionSale(APIController.java:89)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
Change your line to :
final InputStream input = new FileInputStream(resource);
While you're at it, change the name of the parameter resource to path or filePath, since that is what it really is.
The two concepts (file and resource) are related but not the same. A resource can be a file on disk, but it can also be a file inside a jar file or it could be a resource loaded from a remote URL (not often used, but possible).
Since in your case, you know that you want to access a file on disk, you need to use FileInputStream.
See also What's the difference between a Resource, URI, URL, Path and File in Java? for a deeper explanation of the differences between files, resources and related concepts.

Configuration file not found JAVA EE [duplicate]

This question already has answers here:
Where to place and how to read configuration resource files in servlet based application?
(6 answers)
Closed 6 years ago.
I'm trying to load a configuration file. But it doesn't work my configuration file is placed under WEB-INF folder
and here is my code to load that conf file :
private static final String PROPERTIES_FILE = "/WEB-INF/dao.properties";
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
InputStream fichierProperties = classloader.getResourceAsStream(PROPERTIES_FILE);
if (fichierProperties == null) {
throw new DAOConfigurationException("file "+PROPERTIES_FILE+ " not found" );
}
I'm always getting this error file not found, Should make some changes on the build path ??
For simple purpose, try
Put dao.properties inside src folder (where put source code).
Change to
private static final String PROPERTIES_FILE = "dao.properties"; // <-------
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
InputStream fichierProperties = classloader.getResourceAsStream(PROPERTIES_FILE);
if (fichierProperties == null) {
throw new DAOConfigurationException("file "+PROPERTIES_FILE+ " not found" );
}
If you put your file inside the WEB-INF directory, You can use context object to read your file as shown if you have access to servlet context
InputStream input = context.getResourceAsStream("/WEB-INF/dao.properties");

Loading file from resource gives a wrong path [duplicate]

This question already has answers here:
How to get a path to a resource in a Java JAR file
(17 answers)
Closed 7 years ago.
I have a propeties file with a path to a file inside my jar
logo.cgp=images/cgp-logo.jpg
This file already exists:
I want to load this file within my project so I do this:
String property = p.getProperty("logo.cgp"); //This returns "images/cgp-logo.jpg"
File file = new File(getClass().getClassLoader().getResource(property).getFile());
But then when I do file.exists() I get false. When I check file.getAbsolutePath() it leads to C:\\images\\cgp-logo.jpg
What am I doing wrong?
Well a file inside a jar is simply not a regular file. It is a resource that can be loaded by a ClassLoader and read as a stream but not a file.
According to the Javadocs, getClass().getClassLoader().getResource(property) returns an URL and getFile() on an URL says :
Gets the file name of this URL. The returned file portion will be the same as getPath(), plus the concatenation of the value of getQuery(), if any. If there is no query portion, this method and getPath() will return identical results.
So for a jar resource it is the same as getPath() that returns :
the path part of this URL, or an empty string if one does not exist
So here you get back /images/cgp-logo.jpg relative to the classpath that does not correspond to a real file on your file system. That also explains the return value of file.getAbsolutePath()
The correct way to get access to a resource is:
InputStream istream = getClass().getClassLoader().getResourceAsStream(property)
You can use the JarFile class like this:
JarFile jar = new JarFile("foo.jar");
String file = "file.txt";
JarEntry entry = jar.getEntry(file);
InputStream input = jar.getInputStream(entry);
OutputStream output = new FileOutputStream(file);
try {
byte[] buffer = new byte[input.available()];
for (int i = 0; i != -1; i = input.read(buffer)) {
output.write(buffer, 0, i);
}
} finally {
jar.close();
input.close();
output.close();
}

Getting FileNotFoundException even though file exists and is spelled correctly [duplicate]

This question already has answers here:
Java says FileNotFoundException but file exists
(12 answers)
Closed 3 years ago.
I'm creating a small program that will read a text file, which contains a lot of randomly generated numbers, and produce statistics such as mean, median, and mode. I have created the text file and made sure the name is exactly the same when declared as a new file.
Yes, the file is in the same folder as the class files.
public class GradeStats {
public static void main(String[] args){
ListCreator lc = new ListCreator(); //create ListCreator object
lc.getGrades(); //start the grade listing process
try{
File gradeList = new File("C:/Users/Casi/IdeaProjects/GradeStats/GradeList");
FileReader fr = new FileReader(gradeList);
BufferedReader bf = new BufferedReader(fr);
String line;
while ((line = bf.readLine()) != null){
System.out.println(line);
}
bf.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
}
Error line reads as follows:
java.io.FileNotFoundException: GradeList.txt (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileReader.<init>(FileReader.java:72)
at ListCreator.getGrades(ListCreator.java:17)
at GradeStats.main(GradeStats.java:11)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
How about adding:
String curDir = System.getProperty("user.dir");
Print this out. It will tell you what the current working directory is. Then you should be able to see why it isn't finding the file.
Rather than allowing your code to throw, you could check to allow yourself to do something if the file isn't found:
File GradeList = new File("GradeList.txt");
if(!GradeList.exists()) {
System.out.println("Failed to find file");
//do something
}
Please run the below and paste the output:
String curDir = System.getProperty("user.dir");
File GradeList = new File("GradeList.txt");
System.out.println("Current sys dir: " + curDir);
System.out.println("Current abs dir: " + GradeList.getAbsolutePath());
The problem is you have specified only a relative file path and don't know what the "current directory" of your java app is.
Add this code and everything will be clear:
File gradeList = new File("GradeList.txt");
if (!gradeList.exists()) {
throw new FileNotFoundException("Failed to find file: " +
gradeList.getAbsolutePath());
}
By examining the absolute path you will find that the file is not is the current directory.
The other approach is to specify the absolute file path when creating the File object:
File gradeList = new File("/somedir/somesubdir/GradeList.txt");
btw, try to stick to naming conventions: name your variables with a leading lowercase letter, ie gradeList not GradeList

Categories