Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open file in shared mode in Java

Tags:

java

file-io

How to open file in shared mode in Java to allow other users to read and modify the file?

Thanks

like image 223
user851094 Avatar asked Jan 24 '12 09:01

user851094


People also ask

How to open file through Java?

Java FileInputStream class is used to open and read a file. We can open and read a file by using the constructor of the FileInputStream class. The signature of the constructor is: public FileInputStream(File file) throws FileNotFoundException.

How to create and open a file in Java?

We use the method createNewFile() of the java. After creating this object, we call the createNewFile() method with this object. This method creates a new file in Java. Its return type is boolean. It returns true if the file is created successfully, else false if the file with the given name already exists.


2 Answers

In case you're asking about the Windows platform, where files are locked at filesystem level, here's how to do it with Java NIO:

    Files.newInputStream(path, StandardOpenOption.READ)

And a demonstration that it actually works:

    File file = new File("<some existing file>");
    try (InputStream in = Files.newInputStream(file.toPath(), StandardOpenOption.READ)) {
        System.out.println(file.renameTo(new File("<some other name>"));
    }

Will print true, because a file open in shared-read mode may be moved.

For more details refer to java.nio.file.StandardOpenOption.

like image 68
rustyx Avatar answered Nov 03 '22 02:11

rustyx


I'm not entirely sure I know what you mean, but if you mean concurrent modification of the file, that is not a simple process. Actually, it's pretty involved and there's no simple way to do that, off the top of my head you'd have to:

  • Decide whether the file gets refreshed for every user when someone else modifies it, losing all changes or what to do in that case;
  • Handle diffing & merging, if necessary;
  • Handle synchronization for concurrent writing to the same file, so that when two users want to write that file, the content doesn't end up gibberishly, e.g., if one user wants to write "foo" and another one wants to write "bar", the content might end up being "fbaroo" without synchronization.

If you just want to open a file in read-only mode, all you gotta do is open it via FileInputStream or something similar, an object that only permits reading operations.

like image 20
9 revs Avatar answered Nov 03 '22 04:11

9 revs