I am trying to read the files inside a folder, but when I run the program it throws this exception. I tried with some other folders also. It throws the same exception.
Exception in thread "main" java.io.FileNotFoundException: C:\backup (Access is denied)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
Michaël
3,6797 gold badges39 silver badges64 bronze badges
asked Nov 25, 2010 at 22:03
You cannot open and read a directory, use the isFile()
and isDirectory()
methods to distinguish between files and folders. You can get the contents of folders using the list()
and listFiles()
methods (for filenames and File
s respectively) you can also specify a filter that selects a subset of files listed.
answered Nov 25, 2010 at 22:12
rsprsp
23.2k6 gold badges55 silver badges69 bronze badges
0
- check the rsp’s reply
- check that you have permissions to read the file
- check whether the file is not locked by other application. It is relevant mostly if you are on windows. for example I think that you can get the exception if you are trying to read the file while it is opened in notepad
answered Nov 25, 2010 at 22:28
AlexRAlexR
114k16 gold badges130 silver badges208 bronze badges
1
Also, in some cases is important to check the target folder permissions. To give write permission for the user might be the solution. That worked for me.
answered Nov 10, 2014 at 14:55
Here’s a gotcha that I just discovered — perhaps it might help someone else. If using windows the classes folder must not have encryption enabled! Tomcat doesn’t seem to like that. Right click on the classes folder, select «Properties» and then click the «Advanced…» button. Make sure the «Encrypt contents to secure data» checkbox is cleared. Restart Tomcat.
It worked for me so here’s hoping it helps someone else, too.
answered Jun 4, 2018 at 17:46
Check the file path properly, usually we mention the location and forget to specify the file name or the exact position where it belongs to.
answered Mar 6, 2021 at 9:25
I am trying to read the files inside a folder, but when I run the program it throws this exception. I tried with some other folders also. It throws the same exception.
Exception in thread "main" java.io.FileNotFoundException: C:\backup (Access is denied)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
Michaël
3,6797 gold badges39 silver badges64 bronze badges
asked Nov 25, 2010 at 22:03
You cannot open and read a directory, use the isFile()
and isDirectory()
methods to distinguish between files and folders. You can get the contents of folders using the list()
and listFiles()
methods (for filenames and File
s respectively) you can also specify a filter that selects a subset of files listed.
answered Nov 25, 2010 at 22:12
rsprsp
23.2k6 gold badges55 silver badges69 bronze badges
0
- check the rsp’s reply
- check that you have permissions to read the file
- check whether the file is not locked by other application. It is relevant mostly if you are on windows. for example I think that you can get the exception if you are trying to read the file while it is opened in notepad
answered Nov 25, 2010 at 22:28
AlexRAlexR
114k16 gold badges130 silver badges208 bronze badges
1
Also, in some cases is important to check the target folder permissions. To give write permission for the user might be the solution. That worked for me.
answered Nov 10, 2014 at 14:55
Here’s a gotcha that I just discovered — perhaps it might help someone else. If using windows the classes folder must not have encryption enabled! Tomcat doesn’t seem to like that. Right click on the classes folder, select «Properties» and then click the «Advanced…» button. Make sure the «Encrypt contents to secure data» checkbox is cleared. Restart Tomcat.
It worked for me so here’s hoping it helps someone else, too.
answered Jun 4, 2018 at 17:46
Check the file path properly, usually we mention the location and forget to specify the file name or the exact position where it belongs to.
answered Mar 6, 2021 at 9:25
What is the working directory for the program when running on Windows? It is possible that the user context running the program doesn’t have rights to write to c:\Program Files\
.
You did not specify the path to the file so my assumption is that c:\program files\brc\
is the working directory while running the program. Since Windows Vista, you need to have full administration rights to be able to write to the Program Files
and other directories.
Updated: 7/1/2012
Ok, I was able to stub out your program and run it as a main class and was able to have Desktop.getDesktop().open(f);
open a PDF file on Windows 7. I manually put a PDF file into the bin directory where Eclipse compiled my class file to.
I now need to try moving the class file and pdf into a subdirectory of c:\program files\
and see if I get the access denied exception you receive.
Hum, I was able to get Desktop.getDesktop().open(f);
open the PDF file when it was in c:\program files\test\
, see my output below:
C:\Program Files\test>"\Program Files (x86)\Java\jre7\bin\java.exe" MyTestClass
brc2help.pdf exists: 943123 bytes
C:\Program Files\test>dir
Volume in drive C is OS
Volume Serial Number is 2035-793F
Directory of C:\Program Files\test
07/01/2012 10:25 PM <DIR> .
07/01/2012 10:25 PM <DIR> ..
07/01/2012 09:55 PM 943,123 BRC2Help.pdf
07/01/2012 09:57 PM 2,391 MyTestClass.class
2 File(s) 945,514 bytes
2 Dir(s) 567,516,254,208 bytes free
What JRE are you using? Mine is java version "1.7.0_01" Java(TM) SE Runtime Environment (build 1.7.0_01-b08)
Приветствую. Есть файл Input, который создан в документах. Есть программа, которая копирует этот файл в файл Output. Однако при ее выполнение выбрасывается FileNotFoundException и пишет «Отказано в доступе». Пробовал запустить от имени администратора—идея не реагирует вообще никак.
Сама программа:
public void copyFile() {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Приветствуем! Это приложение для копирования файлов.");
System.out.println("Введите имя файла и его расширение");
try {
path = reader.readLine();
} catch (IOException e) {
System.out.println("Такого пути не существует.");
}
System.out.println("Введите размер файла(в байтах)");
try {
fileSize = reader.read();
} catch (IOException e) {
System.out.println("Размер файла некорректный");
}
try(FileInputStream input = new FileInputStream(path);
FileOutputStream output = new FileOutputStream("Output")) {
if (fileSize < 1024) {
byte[] bytes = input.readAllBytes();
output.write(bytes);
} else {
byte[] bytes = new byte[fileSize];
while (input.available() > 0) {
int real = input.read(bytes);
output.write(bytes, 0, real);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// System.out.println("Копирование завершено успешно");
}
}
Что делать?
P. S. Всегда проверяйте ваши пути))
In this blog I will be sharing the reasons due to which you are getting Access is denied i.e, File Not Found Exception, and will solve the error as well. So let’s start and solve this error in your system.
This error occurs for various reasons, let’s discuss them one by one in detail.
1. Opening or Trying to Read a Folder/Directory
It is not possible for the user to see the directory as we do normally and if you try to do that it will result in the exception. Let us check the program written below and the output on the console for better understanding.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
import java.io.File ; import java.io.IOException ; import java.util.* ; import java.io.FileNotFoundException ; import java.io.FileInputStream ; public class filenotfound { public static void main(String[] args) { FileInputStream inputfile = null ; try { File givenfile = new File(«C:/new_file») ; inputfile = new FileInputStream(givenfile); }catch(FileNotFoundException ex) { ex.printStackTrace(); }finally { try { if(inputfile != null) { inputfile.close(); } }catch(IOException ex) { ex.printStackTrace(); } } } } |
Output:
java.io.FileNotFoundException: C:\new_file (Access is denied) at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.<init>(Unknown Source) |
Solution:
In this case, the user needs to be sure that he isn’t attempting the directory for reading.
2. No Permissions for Opening or Reading File
Without having permission it is not possible to read or open the file, if the user is still trying to do so then the exception will occur. Let us check the program written below and the output on the console for better understanding.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
import java.io.File; import java.io.IOException; import java.util.*; import java.io.FileNotFoundException; import java.io.FileInputStream; public class filenotfound { public static void main(String[] args) { FileInputStream inputfile = null; try { File givenfile = new File(«C:/new_file/content.txt»); inputfile = new FileInputStream(givenfile); }catch(FileNotFoundException ex) { ex.printStackTrace(); }finally { try { if(inputfile != null) { inputfile.close(); } }catch(IOException ex) { ex.printStackTrace(); } } } } |
Output:
java.io.FileNotFoundException: C:\new_file\content.txt (Access is denied) at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.<init>(Unknown Source) |
Solution:
Since the user doesn’t have permission to read the file, you need to change the permissions by adding certain lines of code.
Corrected Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
import java.io.File; import java.io.IOException; import java.util.*; import java.io.FileNotFoundException; import java.io.FileInputStream; public class filenotfound { public static void main(String[] args) { FileInputStream inputfile = null; try { File givenfile = new File(«C:/new_file/content.txt»); if(givenfile.canRead() == false) { givenfile.setReadable(true); } inputfile = new FileInputStream(givenfile); }catch(FileNotFoundException ex) { ex.printStackTrace(); }finally { try { if(inputfile != null) { inputfile.close(); } }catch(IOException ex) { ex.printStackTrace(); } } } } |
3. Attempting to Write Inside Read Only File
If the user is trying to write within the read-only file then the exception will come again.
Let us check the program written below and the output on the console for better understanding.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
import java.io.File; import java.io.IOException; import java.util.*; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileInputStream; public class filenotfound { public static void main(String[] args) { FileOutputStream outputfile = null; try { File givenfile = new File(«C:/new_file/content.txt»); outputfile = new FileOutputStream(givenfile); }catch(FileNotFoundException ex) { ex.printStackTrace(); }finally { try { if(outputfile != null) { outputfile.close(); } }catch(IOException ex) { ex.printStackTrace(); } } } } |
Output:
java.io.FileNotFoundException: C:\new_file\content.txt (Access is denied) at java.io.FileOutputStream.open(Native Method) at java.io.FileOutputStream.<init>(Unknown Source) |
Solution:
We will be checking whether the given file already exists or not, if it exists and it is inside the read-only mode then we change it to read and write mode.
Corrected Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
import java.io.File; import java.io.IOException; import java.util.*; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileInputStream; public class filenotfound { public static void main(String[] args) throws IOException { FileOutputStream outputfile = null; try { File givenfile = new File(«C:/new_file/content.txt»); if((givenfile.exists() == true) && (givenfile.canWrite() == false)){ System.out.println(«The File is already existing and currently it is read only mode. Now we are going to make it writable»); givenfile.setWritable(true); } outputfile = new FileOutputStream(givenfile); System.out.println(«The File is available to be overwritten from now onwards»); }catch(FileNotFoundException ex) { ex.printStackTrace(); }finally { try { if(outputfile != null) { outputfile.close(); } }catch(IOException ex) { ex.printStackTrace(); } } } } |
The File is already existing and currently, it is read-only mode. Now we are going to make it writable
The File is available to be overwritten from now onwards.
4. Attempting to Make File Inside Root Folder of Drive
In this case, the user is just simply creating a file inside the root folder but it is resulting in the exception. Let us check the program written below for a better understanding.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
import java.io.File; import java.io.IOException; import java.util.*; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileInputStream; public class filenotfound { public static void main(String[] args) throws IOException { FileOutputStream outputfile = null; try { File givenfile = new File(«C:/content.txt»); outputfile = new FileOutputStream(givenfile); }catch(FileNotFoundException ex) { ex.printStackTrace(); }finally { try { if(outputfile != null) { outputfile.close(); } }catch(IOException ex) { ex.printStackTrace(); } } } } |
Solution:
There are few versions inside Windows in which the systems are not allowing the users to write inside the root of the drive. This can be treated as an unrequired feature or bug in some windows versions. The only solution for this is that you can try to create the file inside the subfolder. Let’s see the corrected code of the above example.
Corrected Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
import java.io.File; import java.io.IOException; import java.util.*; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileInputStream; public class filenotfound { public static void main(String[] args) throws IOException { FileOutputStream outputfile = null; try { File givenfile = new File(«C:/new_file/content.txt»); outputfile = new FileOutputStream(givenfile); }catch(FileNotFoundException ex) { ex.printStackTrace(); }finally { try { if(outputfile != null) { outputfile.close(); } }catch(IOException ex) { ex.printStackTrace(); } } } } |
So I hope the reason for your error was founded above and now it is solved. If you are still facing some errors, then do comment below and we will try to solve them.