[ java on windows ] Access is denied reading file using FileInputStream

Problem : 

Exception in thread "main" java.io.FileNotFoundException: d:/Knowledge/test.txt (Access is denied)Exception in thread "main" java.io.FileNotFoundException: d:/Knowledge/test.txt (Access is denied) at java.io.FileInputStream.open0(Native Method) at java.io.FileInputStream.open(Unknown Source) at java.io.FileInputStream.<init>(Unknown Source) at java.io.FileInputStream.<init>(Unknown Source) at ExcelSheet.setExcelFile(ExcelSheet.java:41) at ExcelSheet.<init>(ExcelSheet.java:28) at Chrome_Browser.main(Chrome_Browser.java:14)

File reading code using FileInputStream

File file = new File("d:/Knowledge/test.txt");
FileInputStream fis = null;
try
{
fis = new FileInputStream(file);
System.out.println("Total file size to read (in bytes) : " + fis.available());
int content;
while ((content = fis.read()) != -1)
{
// convert to char and display it
System.out.print((char) content);
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if (fis != null)
fis.close();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}

Solution : 

  1. Put the following file into user home directory

feel free to change the file path

.java.policy

// Standard extensions get all permissions by default

grant codeBase "file:${{java.ext.dirs}}/*" {
permission java.security.AllPermission;
};

&nbsp;

// default permissions granted to all domains

grant {
permission java.io.FilePermission "d:/Knowledge/test.txt", "read";
};

2. Put the following arguments into VM arguments ( Run > Run configuration )

-Djava.security.manager -Djava.security.policy=security.policy

 

ref : https://stackoverflow.com/questions/23476145/strange-behaviour-of-accesscontroller-checkpermission

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s