Re: Lock a file or somehow make it unwritable
On Jul 31, 11:05 am, Arne Vajh=F8j <a...@vajhoej.dk> wrote:
Lionel van den Berg wrote:
Some experimentation shows that FileOutputStream does
not lock the file exclusively.
But .getChannel().lock() as in your code works (if used
for locking and not for test).
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.channels.FileLock;
public class Lock {
public static OutputStream uselessLock(File f) throws IOExcept=
ion {
return new FileOutputStream(f, true);
}
public static FileLock workingLock(File f) throws IOException =
{
return new FileOutputStream(f, true).getChannel().lock=
();
}
public static void main(String[] args) throws Exception {
File f = new File("C:\\z.z");
f.createNewFile();
//uselessLock(f);
workingLock(f);
OutputStream os = new FileOutputStream(f, true);
os.write(123);
os.close();
}
}
did result in:
Exception in thread "main" java.io.IOException: The process cannot
access the file because another process has locked a portion of the file
which I assume is what you want.
This is interesting. I tried you example, and it works as you said,
however, if you use a PrintStream as follows, there is no exception
and the text is not written:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.channels.FileLock;
/**
*
*/
public class Main {
public static FileLock workingLock(File f) throws IOException {
return new FileOutputStream(f, true).getChannel().lock();
}
public static void main(String[] args) throws Exception {
File f = new File("C:\\Test.txt");
f.createNewFile();
workingLock(f);
PrintStream ps = new PrintStream(f);
ps.print("Test");
ps.close();
}
}