I am trying to initialise a FileInputStream object using a File object. I am getting a FileNotFound error on the line
fis = new FileInputStream(file);
This is strange since I have opened this file through the same method to do regex many times.
My method is as follows:
private BufferedInputStream fileToBIS(File file){
FileInputStream fis = null;
BufferedInputStream bis =null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bis;
}
java.io.FileNotFoundException: C:\dev\server\tomcat6\webapps\sample-site (Access is denied)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.(Unknown Source)
at java.io.FileInputStream.(Unknown Source)
at controller.ScanEditRegions.fileToBIS(ScanEditRegions.java:52)
at controller.ScanEditRegions.tidyHTML(ScanEditRegions.java:38)
at controller.ScanEditRegions.process(ScanEditRegions.java:64)
at controller.ScanEditRegions.visitAllDirsAndFiles(ScanEditRegions.java:148)
at controller.Manager.main(Manager.java:10)
Judging by the stacktrace you pasted in your post I'd guess that you do not have the rights to read the file.
The File class allows you to performs useful checks on a file, some of them:
boolean canExecute();
boolean canRead();
boolean canWrite();
boolean exists();
boolean isFile();
boolean isDirectory();
For example, you could check for: exists() && isFile() && canRead() and print a better error-message depending on the reason why you cant read the file.
You might want to make sure that (in order of likely-hood):
The file exists.
The file is not a directory.
You or the Java process have permissions to open the file.
Another process doesn't have a lock on the file (likely, as you would probably receive a standard IOException instead of FileNotFoundException)
This is has to do with file permissions settings in the OS. You've started the java process as a user who has no access rights to the specific directory.
I think you are executing the statement from eclipse or any java IDE and target file is also present in IDE workspace. You are getting the error as Eclipse cant read the target file in the same workspace. You can run your code from command prompt. It should not through any exception.
Related
For some reason (new to Java), when I'm trying to read an Excel file from my resources folder, it shows that it is there, but when I use FileInputStream to read it I get a FileNotFound Exception. Any ideas?
Code:
public static void openExcelSheet() throws IOException {
FileInputStream fileInputStream = null;
if(applicationSettings.class.getResourceAsStream("/files/Employees.xlsx") != null) {
System.out.println("File Found");
fileInputStream = new FileInputStream("/files/Employees.xlsx");
}else {
System.out.println("File Not Found");
}
XSSFWorkbook workbook = new XSSFWorkbook(fileInputStream);
//int numberOfSheets = workbook.getNumberOfSheets();
System.out.println(workbook.getAllNames());
workbook.close();
}
Here is the Output that I am receiving:
File Found
Exception in Application start method
java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:473)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:372)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:941)
Caused by: java.lang.RuntimeException: Exception in Application start method
at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:973)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:198)
at java.base/java.lang.Thread.run(Thread.java:844)
Caused by: java.io.FileNotFoundException: /files/Employees.xlsx (No such file or directory)
at java.base/java.io.FileInputStream.open0(Native Method)
at java.base/java.io.FileInputStream.open(FileInputStream.java:220)
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:158)
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:113)
at applicationSettings.openExcelSheet(applicationSettings.java:32)
at loginScreen.start(loginScreen.java:70)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:919)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$11(PlatformImpl.java:449)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$9(PlatformImpl.java:418)
at java.base/java.security.AccessController.doPrivileged(Native Method)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:417)
at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
Exception running application loginScreen
The problem seems to be some incorrect assumptions in your code:
if (applicationSettings.class.getResourceAsStream("/files/Employees.xlsx") != null) {
System.out.println("File Found");
fileInputStream = new FileInputStream("/files/Employees.xlsx");
} else {
System.out.println("File Not Found");
}
So this is saying: "if I can find "Employees.xlsx" on the resource path, I can find it in the file system with the same path".
There are two incorrect assumptions here:
You are assuming that since you found "Employees.xlsx" on the resource path will be in the file system at all. This is not a valid assumption:
The resource could be (in fact, typically will be) a member of a JAR file or a similar file.
The resource or the resource's container could have been downloaded on the fly to a temporary file, or into memory.
The resource could have been created on the fly; e.g. by a clever class loader that decrypts or uncompresses something else.
You are assuming that "Employees.xlsx" will have the same resource path as file system path. This is pretty much guaranteed to not be the case. (It can only be the case if you put the root of the filesystem on the classpath ....)
I am not sure why you are trying to do this at all. Per #fabian's answer, POI allows you to open a spreadsheet from a InputStream. You should not need a FileInputStream here.
But in situations where you do need a FileInputStream for a resource on the resource path, the portable solution is to copy the resource to a temporary file, and then open a FileInputStream on the temporary file.
Resources are not necessarily files; They could be stored as entries in a .jar archive. Even if they are stored as files in a directory structure of the file system, the working directory may not match the current working directory. You should use the InputStream returned by getResourceAsStream directly instead of trying to open a new one:
InputStream inputStream = applicationSettings.class.getResourceAsStream("/files/Employees.xlsx");
if (inputStream != null) {
XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
//int numberOfSheets = workbook.getNumberOfSheets();
System.out.println(workbook.getAllNames());
workbook.close();
} else {
System.out.println("Resource not found");
}
Provided that your file is residing inside the project folder, here is the problem remove the slash from the front of the name
fileInputStream = new FileInputStream("Employees.xlsx");
should work then. If it is inside the files folder inside the project folder then
fileInputStream = new FileInputStream("files/Employees.xlsx");
Or you can provide the complete path to the file and that should work
fileInputStream = new FileInputStream("/users/myfolder/files/Employees.xlsx");
I encountered the same issue today, which took me about two hours to partially figured it out. It was so annoying. Depending on how your class code is structured, Java does not allow you to read text file within the method definition. Try reading it in the main method, then take that FileInputStream object as input to your openExcelSheet() method. Let me know if it works :)
I used an ObjectOutputStream to write an object to a file in the same directory as my project's .iml file. The file exists. For some reason, I can't read it using a FileInputStream. I recieve a FileNotFound exception at line 2.
My code is as follows:
File sceneFile=new File("scene.dodge");
FileInputStream fin=new FileInputStream(sceneFile);
ObjectInputStream in=new ObjectInputStream(fin);
return (Scene)(in.readObject());
I've made sure the file scene.dodge is in the project root directory. Any suggestions? I've tried messing around with compiler resource patterns, but I have no idea if that'll do anything. I'm simply stumped.
To read the file from the current directory you need to use ClassLoader#
getResource method.
Load the file like this
URL dodgeSceneURL = classLoader.getResource("scene.dodge");
File sceneFile = new File(dodgeSceneURL.toURI());
FileInputStream fin = new FileInputStream(sceneFile);
I am trying to write a file to internal device storage on my phone (and on user's phones in the future). I was watching a video tutorial from 2016 (https://www.youtube.com/watch?v=EhBBWVydcH8) which shows how he writes output to a file very simply. If you want to see his code, skip forward to 8:23.
Anyway, I basically tried his code, then since that didn't work, I figured would search around.
Apparently, to create a file, I need these lines of code:
String filename = "textfile.txt";
File file = new File(filename);
file.mkdirs();
file.createNewFile();
On the second line, file.createNewFile(), I get the below error:
java.io.IOException: Read-only file system
at java.io.UnixFileSystem.createFileExclusivel
at java.io.UnixFileSystem.createFileExclusivel
at java.io.File.createNewFile(File.java:948)
etc......
And then, if I run my code just by using the lines of code from the tutorial, I get a Null pointer.
Code:
try {
FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE);
fos.write(IDNum.getBytes());
fos.close();
System.out.println("Wrote STuff Outputtt?");
} catch (Exception e) {
e.printStackTrace();
}
Error:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.FileOutputStream android.content.Context.openFileOutput(java.lang.String, int)' on a null object reference
at android.content.ContextWrapper.openFileOutput(ContextWrapper.java:199)
at com.lecconnect.lockoutdemo.FileManager.AddUser(FileManager.java:37)
Line 37 is the first line in the try/catch.
Please let me know if you require any additional information to assist me. Your replies are greatly appreciated.
It is important to separate the directory and the file itself.
In your code, you call mkdirs on the file you want to write, which is incorrect usage because mkdirs makes your file into a directory. You should call mkdirs for the directory only, so it will be created if it does not exist, and the file will be created automatically when you create a new FileOutputStream object for this file.
Try this one:
File directory = getFilesDir(); //or getExternalFilesDir(null); for external storage
File file = new File(directory, fileName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
fos.write(IDNum.getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
When I try and load up a .txt file in my code, I get this error:
java.io.FileNotFoundException: file:\C:\Users\Me\Desktop\Program.jar!\test\foo.txt (The filename, directory name, or volume label syntax is incorrect)
My code for loading these files is this:
try {
String path = getClass().getResource(file).getPath();
BufferedReader reader = new BufferedReader(new FileReader(path));
...
} catch(IOException e) {
System.err.println("Could not read file!");
e.printStackTrace();
System.exit(-1);
}
And the string I load into the method is this:
foo.txt
Even though I've checked many times, the file exists in that exact path, yet my program still can't find it. And why is there an exclamation mark at the end of Program.jar? Is it important?
Thank you to anyone who helped answer my questions.
If you launch it out of jar in console, you better access your resource as a InputStream and process it the desired way. When you enter the actual path(especially not relative) - you are trying to get to the file that is INSIDE the jar, which is wrong.
Here's close (pseudo) code for your problem:
InputStream resource = ClassName.class.getResourceAsStream("/test/foo.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(resource));
//do some stuff
resource.close();
reader.close();
The exclamation mark is a separator the JVM uses to note the .jar file in the path.
I have parsed a batch of XML Schema files using a DOMparser. I than added several annotations, which are essential for the application I am creating. I then want to write these new "preprocessed" files to a new location, and I get a FileNotFound exception (access denied).
Here's the snippet of code where I am writing the file:
Transformer tFormer = TransformerFactory.newInstance().newTransformer();
// Set output file to xml
tFormer.setOutputProperty(OutputKeys.METHOD, "xml");
// Write the document back to the file
Source source = new DOMSource(document);
File preprFile = new File(newPath(xmlFile));
// The newPath function is a series of String operations that result in a new
relative path
try {
// Create file if it doesn't already exist;
preprFile.mkdirs();
preprFile.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
Result result = new StreamResult(preprFile);
tFormer.transform(source, result);
And the error I am getting is the following:
java.io.FileNotFoundException: absolutePathHere (Access is denied)
Which points to this line in the above snippet :
tFormer.transform(source, result);
I'm using a Windows machine (read somewhere that that can be the source of this error), and I've already tried turning UAC off, but no success.
I was thinking maybe the createNewFile() method doesn't release the file after it's been made, but was unable to find more information about that.
Here's hoping StackOverflow can come to my rescue once again.
It's probably running under a user account that doesn't have the rights to that directory.
You said "The directory is created, and it appears the file is created as a directory as well". So I think it creates directory named 'wsreportkbo_messages.xsd'
It gives you error may be because you are trying to read directory. You can list files in directories using listFiles().
You cannot open and read a directory, use the isFile() and isDirectory() methods to distinguish between files and folders.
I found the solution:
File preprFile = new File(directory1/directory2/directory3/file.xsd);
File directory = new File(directory1/directory2/directory3/);
try {
// Create file if it doesn't already exist;
directory.mkdirs();
preprFile.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
Thanks for the help.