How to open file in shared mode in Java to allow other users to read and modify the file?
Thanks
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.
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.
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
.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With