Folder Locking using java

Hi All,
I want to implement the folder locking using java.But i can't find any method to implement my requirement. I find one method to lock a file using FileChannelObject.tryLock() or FileChannelObject.lock() methods of FileLock class. But the main problem is that FileChannel object is coming through only by calling getChannel() method on a RandomAccessFile object or FileInputStream object only.
If i want to lock a folder i am not able to create the lock on it. So please provide me any example to create a lock on  a directory.
Thanks in advance.

JNI isn't magic. It can only call the operating system. The question is, is there really an operating system API that would let you do it.?

Similar Messages

  • How to ZIP the files and folders/sub folder files using java

    HI All,
    I'm New to this Forum, Could anybody tell me how to zip the files and folders/sub folders using java. For example I have a folder with the name testfolder and side that folder I have some files and some sub folders inside subfolders I have some other files. I need to ZIP the files and folders as they are in same hierarchy.
    Any pointers or help wolud be appritiated.
    Thanks,
    Rajeshbabu V

    [http://www.devx.com/tips/Tip/14049]

  • Setting folder permission using java

    Hi,
    I want to set permissions for a folder based on the user id. Can i do it using java ? if yes, please let me know how can we do that.
    Thanks in advance.

    Depends on what you mean. If you want to programatically include/exclude a folder in a, say, File Open dialog that your program displays, then yes, absolutely. If you're asking whether can set an operating system security flag on a folder, then the answer is probably not (at least not without resorting to native code), and it will almost certainly not be portable across different operating systems.

  • File Locking using java.nio package

    I am trying to lock a file using FileChannel's lock method on a CIFS file system. My application is on windows and the CIFS is accessed using UNC format ( \\1.2.3.4\blah.. ). I get the following error
         java.io.IOException: The network request is not supported
         at sun.nio.ch.FileChannelImpl.lock0(Native Method)
         at sun.nio.ch.FileChannelImpl.lock(FileChannelImpl.java:750)
         at java.nio.channels.FileChannel.lock(FileChannel.java:865)
    From the same machine using the same UNC formatm, when I lock the file using windows C API, I can successfull lock.
    Anyone has any idea why JVM can not lock even using nio package. Shouldnt it use the same ( or similar ) API under the hood as its clear by the package name java.nio
    The C program I am using is
    #include <io.h>
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <sys/locking.h>
    #include <share.h>
    #include <fcntl.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    void main( int argc, char **argv )
    int fh,numread;
    char buffer[40];
    char filename[500];
    /* Quit if can't open file or system doesn't
    * support sharing.
    if ( argc > 1 )
              strcpy(filename,argv[1]);
    else
              strcpy(filename,"locking.c");
    fh = sopen(filename , O_RDWR, SHDENYNO, //_SH_DENYRW,
    SIREAD | SIWRITE );
    if( fh == -1 )
    exit( 1 );
    /* Lock some bytes and read them. Then unlock. */
    if( locking( fh, LKNBLCK, 30L ) != -1 )
    printf( "No one can change these bytes while I'm reading them\n" );
    numread = _read( fh, buffer, 30 );
    printf( "%d bytes read: %.30s\n", numread, buffer );
    lseek( fh, 0L, SEEK_SET );
         printf( "Press a key to unlock the file.....\n" );
         getchar();
         locking( fh, LKUNLCK, 30L );
    printf( "Now I'm done. Do what you will with them\n" );
    else
    perror( "Locking failed\n" );
    _close( fh );
    }

    It uses LockFile and LockFileEx. Please check in the MSDN documentation the peculiarities of such APIs.
    JNIEXPORT jint JNICALL
    Java_sun_nio_ch_FileChannelImpl_lock0(JNIEnv *env, jobject this, jobject fdo,
                                          jboolean block, jlong pos, jlong size,
                                          jboolean shared)
        jint fd = fdval(env, fdo);
        HANDLE h = (HANDLE)_get_osfhandle(fd);
        DWORD lowPos = (DWORD)pos;
        long highPos = (long)(pos >> 32);
        DWORD lowNumBytes = (DWORD)size;
        DWORD highNumBytes = (DWORD)(size >> 32);
        jint result = 0;
        if (onNT) {
            DWORD flags = 0;
            OVERLAPPED o;
            o.hEvent = 0;
            o.Offset = lowPos;
            o.OffsetHigh = highPos;
            if (block == JNI_FALSE) {
                flags |= LOCKFILE_FAIL_IMMEDIATELY;
            if (shared == JNI_FALSE) {
                flags |= LOCKFILE_EXCLUSIVE_LOCK;
            result = LockFileEx(h, flags, 0, lowNumBytes, highNumBytes, &o);
            if (result == 0) {
                int error = GetLastError();
                if (error != ERROR_LOCK_VIOLATION) {
                    JNU_ThrowIOExceptionWithLastError(env, "Lock failed");
                    return sun_nio_ch_FileChannelImpl_NO_LOCK;
                if (flags & LOCKFILE_FAIL_IMMEDIATELY) {
                    return sun_nio_ch_FileChannelImpl_NO_LOCK;
                JNU_ThrowIOExceptionWithLastError(env, "Lock failed");
                return sun_nio_ch_FileChannelImpl_NO_LOCK;
            return sun_nio_ch_FileChannelImpl_LOCKED;
        } else {
            for(;;) {
                if (size > 0x7fffffff) {
                    size = 0x7fffffff;
                lowNumBytes = (DWORD)size;
                highNumBytes = 0;
                result = LockFile(h, lowPos, highPos, lowNumBytes, highNumBytes);
                if (result != 0) {
                    if (shared == JNI_TRUE) {
                        return sun_nio_ch_FileChannelImpl_RET_EX_LOCK;
                    } else {
                        return sun_nio_ch_FileChannelImpl_LOCKED;
                } else {
                    int error = GetLastError();
                    if (error != ERROR_LOCK_VIOLATION) {
                        JNU_ThrowIOExceptionWithLastError(env, "Lock failed");
                        return sun_nio_ch_FileChannelImpl_NO_LOCK;
                    if (block == JNI_FALSE) {
                        return sun_nio_ch_FileChannelImpl_NO_LOCK;
                Sleep(100);
        return sun_nio_ch_FileChannelImpl_NO_LOCK;
    }

  • Want to create a new folder in Windows using Java?

    Hello everyone!!!
    The situation is I want to create a folder using Java.
    What I am doing is I am asking client to upload files.If the client is uploading for the first time a new folder is created on the server side and all the files related with that client will be uploaded in that folder only.Can anyone help me with the code.I am using html for letting client select the file to be uploaded and jsp to upload the file .The server I am using is Tomcat5.5 and OS is Windows Xp.
    Please help me with the code or any alternate logic.
    Thanks in advance.

    create a java.io.File object for the path you'd like your directory to have and call .mkdir() on it (or mkdirs() if you need to create a hierarchy of directories).

  • How to create a directory or Folder  using java program?

    Hi all,
    Can any one know, how to create a directory(new folder) in java.
    can any give me some idea, on creating a directory using java program dynamically.
    thanx in advance

    hi thanks for your answer,
    sorry, actual i know this technique(its my fault i didnt mentioned it)
    i am looking for some what different technique.
    bye
    ram

  • Creating a folder in current workspace using java code

    Hi Experts,
    I need to create a folder and some file in the workspace of NWDS user. Can someone please suggest how can i find out the workspace of user using JAVA code.
    IWorkspaceRoot is not working in NWDS.
    Regards
    Pranav

    Hi Pranav,
    Tell me if you want to create this folder at run time or in NWDS while developing application.
    If you want to create it at the time of development just change your perspective to Java perspective and from there you can see the entire project structure and from there you can create desired files / folders.
    Ninad

  • How to create a Folder using java.

    Hi All,
    I have a doubt. I want to create a folder using java.
    Inputs are the destination where the folder should be created and the name of the folder. Plz help me in this regard.
    thanks and regards,
    Vincent .R.

    check out javadoc for java.io
    File reldir=new File("NewDir");//relatively where your program runs
    reldir.mkdir();
    File absdir=new File("C:/NewDir");//absolute path
    reldir.mkdir();
    File newdir=new File(absdir,"SubDir");//defines another dir under absdir
    newdir.mkdir();
    Gil

  • Open, Open Containing Folder in Windows Explorer Using java

    How to open a file using the default application using java code?
    Ex: - Open a JPG file using its default image viewer (Ex: Piscasa 3)..... (Not Inside the Java Application)
    Then how to open a file containing folder with that file selected?
    Couldn't find any sources in the internet, Not sure whether my search terms are correct....
    Please Help
    Thanks!!!

    Madushan.UoM wrote:
    Thanks Andrew...
    I've did opening the file using
    try {
    Desktop desktop = null;
    if (Desktop.isDesktopSupported()) {
    desktop = Desktop.getDesktop();
    desktop.open(new File(path));
    } catch (IOException ioe) {
    ioe.printStackTrace();
    }Also able to open the directory by setting the "path" variable into the directory path
    But how to highlight the needed file after the Explorer is opened???Also, to be completely safe, you'd want to call Desktop#open() only if isDesktopSupported() returns true, otherwise you'll get a NullPointerException.
    if (Desktop.isSupported()) {
       try {
          Desktop.getDesktop().open(new File(path));
       } catch (IOException ioe) {
          ioe.printStackTrace();
    }

  • Unzipping Files in Folder using Java

    Hello,
    I am working on a project and I am having trouble writing a program that will unzip all the files in a given directory (using Java). The directory is known, but the name and number of files to be unzipped will vary on each execution. The files need to be unzipped and then placed in a different specified folder.
    Thank you for your assistance.

    This should give you some idea. Be sure to import java.util.zip.
        /** unzipDirArchive */
        public static void unzipDirArchive(File inFile)
            throws IOException {
            ZipEntry entry = null;
            // Create stream to read the compressed file.
            ZipInputStream zis = new ZipInputStream(new FileInputStream((inFile)));
            // Create stream to write the output file.
            FileOutputStream fos = null;
            byte buffer[] = new byte[4096];
            int bytesRead;
            boolean dirCreated = false;
            // For each entry in the ZIP input file.
            while ((entry = zis.getNextEntry()) != null) {
                // If we have not created the enclosing directory.
                if (!dirCreated) {
                    // Create the directory.
                    int endIndex = entry.getName().lastIndexOf('/');
                    String dirName = entry.getName().substring(0, endIndex);
                    // DEBUG
                    // System.out.println("dirName is: " + dirName + ".");
                    File newDir = new File(dirName);
                    // Check if the output dir already exists.
                    if (newDir.exists()) {
                        System.err.println("Uncompress: Output directory " + dirName +
                                           " already exists.");
                        System.exit(-5);
                    else {
                        // If we successfully created the enclosing directory.
                        if (newDir.mkdir()) {
                            dirCreated = true;
                        else {
                            System.err.println("Uncompress: Cannot create directory " +
                                                dirName + ".");
                            System.exit(-6);
                    } // end if newDir.exists
                } // end if !dirCreated
                System.out.println("Inflating: " + entry.getName());
                fos = new FileOutputStream(entry.getName());
                // Copy the data from the ZIP file entry to a file.
                while((bytesRead = zis.read(buffer)) != -1)
                    fos.write(buffer, 0, bytesRead);
                fos.close();
            } // end while more entries in the ZIP file
            zis.close();
        } // end method unzipDirArchive

  • Want to hide a folder using Java

    I want to hide a folder using Java. Can anyone give me API to do this.
    I have checked the I/O package in that only isHidden() is there which shows if the file is hidden or not. But i want to hide a folder using Java code.
    Can you please help me.
    Thanking you in advance

    If your dealing with a Linux directory you could hide it by prepending a dot. Or, if a directory of that name already exists, prepending a number of dots. Unhiding would consist of removing all the leading dots (and this operation might not always be possible).
    If it's a Windows directory you might want to look at the "attrib" command.
    [http://www.computerhope.com/attribhl.htm]

  • Set Folder Presentation LayoutSet using Java

    HI
    I need to set the presentation layoutset using Java.
    Can somebody guide me as to how the API can be used?
    I discovered this inteface 'ILayoutSetEvent' in the package 'com.sapportals.wcm.rendering.base' that has the methods 'getLayoutSet()' and 'setLayoutSet()'.
    However, i do not know how to get a handle on this for a particular folder.
    Any help would be appreciated.
    Thanks
    Alkesh

    Hello,
    I'm not sure if the API is officially released, but ...
    You need the ILayoutService, which is a repository service. There your can either set a profile or a layoutset for a folder (collection).
    public boolean saveParametersForCollection(
       ICollection collection,
       ILayoutSet parameters,
       ILayoutContext context);
    The paramter 'collection' is the folder, for which you want to save the settings.
    The parameter 'context' is a key for the iView you want to have the settings in. If you want to have the same settings for this folder in all iViews, you may use null.
    The parameter 'parameters' is the map with all settings you want to save. This may be in the simplest way only the name of the layoutset.
    The coding may look like:
    import com.sapportals.wcm.repository.service.layout.*;
    import com.sapportals.portal.pcd.gl.IPcdGlService;
    import com.sapportals.portal.prt.component.IPortalComponentRequest;
    import com.sapportals.portal.prt.runtime.PortalRuntime;
    import com.sapportals.wcm.IWcmConst;
    import com.sapportals.wcm.repository.ICollection;
    import com.sapportals.wcm.repository.ResourceException;
    import com.sapportals.wcm.repository.ResourceFactory;
    import com.sapportals.wcm.repository.service.layout.customizing.ILayoutSet;
    import com.sapportals.wcm.repository.service.layout.customizing.IParameterNameConst;
    import com.sapportals.wcm.repository.service.layout.customizing.flavor.IFlavorConst;
    public class SettingsUtil {
      public static void saveLayoutset(String layoutSetID, ICollection collection, IPortalComponentRequest req) {
        try {
          // get the layout service
          ILayoutService layoutService = (ILayoutService) ResourceFactory.getInstance().getServiceFactory().getRepositoryService(collection,
              IWcmConst.LAYOUT_SERVICE);
          // check for null, class cast...
          // get the context
          ILayoutContext context = null;
          try {
            String name = req.getComponentContext().getProfile().getComponentName();
            // get a short iView id from the GLService if possible
            IPcdGlService service = (IPcdGlService) PortalRuntime.getRuntimeResources().getService(IPcdGlService.KEY);
            String shortContextID = service.getPcdObjectFactory().convertUrlToShortName(name);
            context = layoutService.getContextForUser(collection.getContext().getUserUME(), shortContextID);
          } catch (IllegalArgumentException e) {
            // handle exception
          ILayoutSet layoutSet = layoutService.createLayoutSet();
          try {
            layoutSet.setParameter(IFlavorConst.FLAVOR_NULL, IParameterNameConst.SETNAME, layoutSetID);
          } catch (LayoutServiceConfigLoadException e1) {
            // handle exception
          // save the settings for the folder
          layoutService.saveParametersForCollection(collection, layoutSet, context);
        } catch (ResourceException e) {
          // handle exception
    This is only a sceleton. Use with care.
    ShortcontextID or User may be null.
    regards
    Andreas

  • Open Folder by double click using java.awt

    Hello Guys,
    I have a problem. I m listing directory in List(java.awt). When i single click on directory it will open. But how i can double click on that directory then and then it will open otherwise not. By using JAVA.AWT.

    According to the documentation for java.awt.List "When an item is selected or
    deselected by the user, AWT sends an instance of ItemEvent to the list. When
    the user double-clicks on an item in a scrolling list, AWT sends an instance of
    ActionEvent to the list following the item event. AWT also generates an action
    event when the user presses the return key while an item in the list is selected."
    If your directories are "opening" (whatever that means) in response to a single
    click, that it because of how you have written your code. Change it so that action
    events rather than item events cause the opening to happen.

  • How to create  and hide a drive using java?

    I want to ask how to create a temporary drive/ or a drive by allocating some space of existing drives(eg allocating some space of C: Drive such as 5mb for storing files on the new drive that has been created) and then i want to hide that drive .So Please can anyone Explain me how to do that.

    Iam saying to all of you iam not blaming to anyone even java. And my harddisk is not currepted or damage by using that. My harddisk is working properly. But i don't know why all of you think that i am blamming to someone but iam asking some question which need to be answered.
    I am clearing all of you i am a student and iam creating an project in java for that i need this. I also want to add File/Folder lock on that project. This technique i have seen in folder lock 6 software that they use hidden drive to store files. Thats why iam asking that how to apply this technique using java.
    And plz plz read this carefully and answer me to solve my problem.

  • How to save report in PersonalCategory  after creating it using java panel?

    Hi,
    Anybody knows How to save report in PersonalCategory  after creating it using java panel?
    I dont want to save it in public folder. I want to save report (webi) in user's personal category.
    can anybody send me source code?
    It will help me a lot.
    Thanks in advance
    Amol Mali

    Hi teda,
    i'm assuming that you have seen my post that i did successfuly save report in user's personal category.
    Actually the report is created in webi java panel using RE SDK and  is saved in Report Sample Folder then i'm saving it in user's personal category by following code
    string query = "Select SI_PERSONAL_CATEGORIES From CI_INFOOBJECTS Where "
                         + "SI_INSTANCE=0 And SI_ID=" + reportID;
                    InfoObjects infoObjects = infoStore.Query(query);
                    InfoObject infoObject = infoObjects[1];
                    Webi wreport = (Webi)infoObject;
                    ObjectRelativeIDs personalIDs = wreport.PersonalCategories;
                /personalIDs.Add(Convert.ToInt32(categoryID));
                   infoStore.Commit(infoObjects);
    But the report is presents in the Folder also and in user's personal category also.
    I dont want the report to be in the folder (Report Sample) if i saved it in user's personal category.
    How can i do that?
    any idea.
    Please help me.
    Thanks in advance
    Amol Mali
    Edited by: amol mali on Jan 9, 2009 7:55 PM

Maybe you are looking for