Reputation: 1715
I do not understand why Java don't want to delete the file! I basically want to lock a file to avoid that my jar-file can start more than one time. Then after the action I want to delete the lock-file, but this seems for some reason not to be possible.
Here is the code:
package footballQuestioner;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.nio.channels.FileLock;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class attempter
{
public static void main(String[] args) throws FileNotFoundException, IOException
{
Ausgabe ausGabe=new Ausgabe();
}
class Ausgabe
{
public Ausgabe()
{
tryToStart();
}
public boolean tryToStart(){
File file1=new File("C:\\Users\\laudatio\\Downloads\\erzFeind.txt");
RandomAccessFile in=null;
FileLock fileLock=null;
file1.setWritable(true);
try
{
file1.createNewFile();
in = new RandomAccessFile(file1, "rw");
fileLock = in.getChannel().tryLock();
if(fileLock == null)
return false;
}
catch (Exception e)
{
e.printStackTrace();
}
file1.delete();
return true;
}
}
Upvotes: 1
Views: 111
Reputation: 533442
You can't delete a file you have open. This is a limitation of Windows. You must first close it. try
file1.close();
file1.delete();
Note: Unix doesn't do this, it not a Java "feature"
Upvotes: 2