Ola , alguém jah usou isso ou sabe porque está dando erro esse código?
O codigo serve pra fazer um lock antes de salvar num arquivo.
Ele cai na Exception que escreve “##### Erro 2” dando o seguinte saida:
Erro 2
java.io.IOException: Invalid argument
at sun.nio.ch.FileChannelImpl.lock0(Native Method)
at sun.nio.ch.FileChannelImpl.tryLock(FileChannelImpl.java:528)
at java.nio.channels.FileChannel.tryLock(FileChannel.java:967)
A linha onde dá a exception é : lock = channel.tryLock();
SOURCE
************************************************************* private File file;
private FileChannel channel = null;
private RandomAccessFile raf = null;
private FileOutputStream fos = null;
private Writer writer = null;
private FileLock lock = null;
private int retrynum = 3;
public synchronized void writeLogEntry(int level, String message)
{
String entry = “oi”;
try {
fos = new FileOutputStream(file, true);
writer = new OutputStreamWriter(fos, "UTF-8");
// get a file channel to the file
channel = fos.getChannel();
}
catch (Exception ex)
{
ex.printStackTrace();
}
//Try acquiring an exclusive lock N times and gives up
while ( retrynum > 0 )
{
try{
lock = channel.tryLock();
if ( lock != null )
{
try
{
writer.write(entry);
writer.close();
break;
}
catch (Exception ex)
{
System.out.println("##### Erro 1");
ex.printStackTrace();
break;
}
finally
{
lock.release();
channel.close();
}
}
Thread.sleep(2000);
retrynum--;
}
catch (Exception ex)
{
System.out.println("##### Erro 2");
ex.printStackTrace();
break;
}
}
retrynum = 3;
}