Limiting file access in Java

In my Java application (not an applet) I wish to limit certain file operations to all classes except a list/group/package of classes that should not be restricted.

Specifically, I would like to limit…

  • File reads
  • File writes
  • File creation
  • File deletion

…such that they can only be done within the current working directory for all but the unrestricted classes.

SecurityManager attempt:
I have tried to implement a subclass of the SecurityManager class that implements this behaviour, however it seems that when checks are made the file information provided does not give more than just the filename (unless I am missing something?).

Also, I don’t quite understand how in this case I could find out the class which the call is being made from, to allow me to determine whether to allow the operation or throw an exception. Is there any way I could get all the information I need for this approach to work?

Policy-based attempt:
I am also aware that Java policies are intended for restricting the actions of classes, including things such as file operations. However, I’ve really struggled to find a good resource to learn how I could go about solving my problems using a .policy file.

Summarisation of question:

1) Are there any alternative approaches that may be preferable to those I’ve mentioned?

2) Is this possible using a SecurityManager? Am I missing out on how I should actually be implementing such an approach?

3) Is this possible using a policy file? Are there any good resources I’ve missed on this front?

I’m really not adversed to any amount of hard work I need to invest in achieving this- I’m just unsure as to how I should approach it properly. I’m also sorely lacking in good resources to teach me enough about the two possible approaches I’ve mentioned, to allow me to implement it myself. Above all, I’m not afraid of significant reading where required!

Thanks for any help you can give, in advance.


Here is how you can do it using a policy file.

Create a Java file that can act with privileges:

package egPriv;


public class PrivCat {
    /** Cat a file with no privileges */
    public void cat(String file) throws IOException {
        cat(new FileReader(file));

    private void cat(Reader r) throws IOException {
        int c;
        while( (c = != -1 ) {
            System.out.print((char) c);

    /** Cat a file WITH privileges */
    public void catPriv(final String file) throws IOException {
        Reader r;
        try {
            r = AccessController.doPrivileged(new PrivilegedExceptionAction<Reader>() {
                public Reader run() throws IOException {
                    return new FileReader(file);
        } catch (PrivilegedActionException e) {
            throw (IOException) e.getCause();

Create a regular file for demonstating

package eg;

import egPriv.PrivCat;


public class Cat extends PrivCat {
    public static void main(String[] args) throws IOException {
        Cat eg2 = new Cat();
        System.out.println("Processing with privilege:");

        System.out.println("Processing normally");[0]);

Create sample.policy file:

/* anyone can read write and execute within current working dir */
grant {
  permission "${user.dir}", "read,write,execute";

grant {
  permission "${user.dir}/*", "read,write,execute,delete";

/* Only code from this jar can work outside of CWD */
grant codebase "file:egPriv.jar" {
  permission "<<ALL FILES>>", "read,write,execute,delete";

Compile and then Test:

jar cvf egPriv.jar egPriv
jar cvf eg.jar eg

echo 'Restricted' > ..file.txt
java -cp eg.jar;egPriv.jar  eg.Cat ..file.txt

echo 'Open' > file.txt
java -cp eg.jar;egPriv.jar  eg.Cat file.txt

Android project package structure

I am wondering, how to create flexible package structure for an Android application, such that it’ll be easy to extend and manage. My first idea is to put each application component in separate package, such as:

spk.myapp.main.(all classes used in Main activity)
spk.myapp.processor.(all classes used by Processor provider)

…and so on. However, the aspect I don’t like is, that the class and package naming convention may quickly became inconsistent with other fully qualified names, such as provider authorities (in this case I would rather name these spk.myapp.processor than spk.myapp.processor.processor as the class package path would suggest).

I’ve done some research, but most pages explain the initial project directory structure, rather than suggest one for bigger projects.

My problem might sound silly, but I like to have order in my projects from the beginning, such that further managing and expanding them doesn’t involve unnecessary refactorings or cleanups. Also, I do not have much experience in Java and I wish to learn good habits from the beginning.

Does one have a good and reliable project package structure and naming conventions for Android projects?


Wikipedia has useful notes on Java packages. Packages are mainly useful for two reasons:

  1. A package provides a unique namespace for the types it contains.
  2. Classes in the same package can access each other’s package-access members.

The first point means that you can group items by logical functionality. Activities could reside under an activity package, and your services under a service package.

The second point is quite important and often overlooked. Package access allows you to do some clever things. For example, you can have a ‘builder’ class which can build and populate models which have package access properties, without adding lots of setter methods or using public properties. This can make object creation really simple and intuitive, while objects remain immutable outside the package.

A really good example of this principle can be found in Romain Guy’s Shelves app. The BookStore class can create Book objects and modify their members, without exposing these fields to other classes (in other packages).


Lucene QueryParser in multiple threads: synchronize or construct new each time?

I have a web application where users submit queries to a Lucene index. The queries
are parsed by a Lucene
QueryParser. I learned the hard way that QueryParser is not thread-safe.

Is it better to use a single QueryParser instance, and synchronize on calls to its parse() method? Or is it better to construct a new instance for each query? (Or would I be better served by a pool of QueryParsers?)

I know that in general questions like this depend on the particulars and require profiling, but maybe someone out there can say definitively “QueryParsers are extremely inexpensive/expensive to construct”?


Create a new one each time. These are lightweight objects and the JVM handles object creation and garbage collection very well. Definitely do not use an object pool.


How to write and run scripts in the Google Chrome Javascript Console?

I recently switched from Firefox to Chrome and I (probably) missed an important feature. I was used to test javascript snippets on FF from within the Firebug console this way: open the console, write the script and finally press CTRL + Return to execute the code.

It seems not possible to do the same in Chrome console, as when I type some code there and press return to start a new line the code is executed immediatly.

Is there a way to replicate the Firefox behavior on Chrome?



Install Firebug Lite for Google Chrome. It has got a console.
Don’t look for a full fledged Firebug. You will be disappointed 🙂

Oops,I didn’t read properly at first. My bad!

In Firebug Lite, take Console. Then you will see a tiny red up-arrow at the right corner.
Click on it and you will get a multi-line console. Won’t you?


Is it possible to use CamcorderProfile without audio source?

My code:

mediaRecorder = new MediaRecorder();


CamcorderProfile profile = CamcorderProfile.get(QUALITY_LOW);

It works. But I need to record only video.

And if I don’t use mediaRecorder.setAudioSource(), mediaRecorder.setProfile() fails with IllegalStateException.

Any idea?


From MediaRecord.setProfile:

public void setProfile(CamcorderProfile profile)

Since: API Level 8 Uses the settings from a CamcorderProfile object for recording. This method should be called after the video AND audio sources are set, and before setOutputFile().

From Android – CamcorderProfile docs

Each profile specifies the following set of parameters:

  • The file output format
  • Video codec format
  • Video bit rate in bits per second
  • Video frame rate in frames per second
  • Video frame width and height,
  • Audio codec format Audio bit rate in bits per second
  • Audio sample rate
  • Number of audio channels for recording.

I’d say you could read the relevant video-related settings from a desired CamcorderProfile and set them explicitly yourself.

Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..