Hey guys, I am trying to delete a file. I don't understand why its not working.

public void Refresher()throws IOException
    {
    	File theFile=new File("C:\\theFile.txt");
    	theFile.delete();
    }

I launcher it with Refresher(); I googled around and followed a tutorial. (My code is compiles correctly)

Thanks PO

try this

File file = new File("C:/theFile.txt");
		file.delete();

This works fine.

import java.io.File;
import java.io.IOException;

/**
 * Delete a file from within Java
 * 
 * @author Ian F. Darwin, http://www.darwinsys.com/
 * @version $Id: Delete.java,v 1.5 2004/02/09 03:33:47 ian Exp $
 */
public class Delete {
  public static void main(String[] argv) throws IOException {

    // Construct a File object for the backup created by editing
    // this source file. The file probably already exists.
    // My editor creates backups by putting ~ at the end of the name.
    File bkup = new File("C:\\test.txt");
    // Quick, now, delete it immediately:
    bkup.delete();
  }
}

Is there anything else you do with the file before deleting? Like using for temporary writing?

commented: Lots of help thanks! +1

That did it! Thanks!

Okay I lied not fixed, Yes I read the file before I delete and I also write to it in another Java program that is used before it.

Do you want to share the code, or it is not possible as you do not want get accused of plagiarism by your teacher and therefore we need to work it out blind folded?

I am using it at my workplace (internet cafe), and the reason for the program is because it is to expensive to buy commercial accounts for all of our computers so I have a program that runs when they launch an application which grabs an account number from a MySQL DB. Then it sets the account available field to one for that account number so other computers wont grab that account number. The program saves the account number to a text file so that when the user logs off it runs another program which grabs the account number, connects to the MySQL database and frees the account up so another person can use it. Here is all my code:

This is the initial file that runs when the they try and launch the program:

/**
 * This program is designed for a smart login system for the steam engine.
 * It will connect to a server grab a available account number and use it to log in
 * then will set that account to in use.
 * The purpose is to make all 17 of our steam accounts work on every computer so
 * users do not have to shuffle around to play steam.
 */
import javax.swing.*; //Used for JOption Panes
import java.sql.Statement;// Statement class
import java.io.*;
import java.sql.Connection;//MySQL connection Initiate
import java.sql.DriverManager;//Driver manager
import java.sql.SQLException;//SQLexception class
import java.sql.ResultSet;


public class SteamChecker
{
    public SteamChecker() throws IOException, SQLException 
    {
    	SteamRefresher();//Deletes the file that holds the current account number that's in use before it sets a new one
    	Statement stmt = null;//This creates a statement variable
    	Connection con = null; //Connection variable
    	ResultSet rs;// result set variable
    	//tries to connect to the database.
    	try {
    	      Class.forName("com.mysql.jdbc.Driver").newInstance();
    	      con = DriverManager.getConnection("jdbc:mysql://IP ADDRESS:3306/dbNAME", "USERNAME", "PASSWORD");

    	      //TESTING START
    	      stmt = con.createStatement();
    	      //stmt.executeUpdate("UPDATE `dbNAME`.`accounts` SET `available` = '1' WHERE `accounts`.`autoid` =1 LIMIT 1 ;");
    	      //TESTING FINISH

    	    } catch(Exception e) {
    	      System.out.println("Exception: " + e.getMessage());
    	    }
    	
    	//Setting variables
        boolean accountVerified=false;
        //int inUse=1, accountCount=1;
        int accountNumber=0;
        
        //Gets everything from accounts table
        rs = stmt.executeQuery("SELECT * from accounts ORDER BY autoid");
        
        //Test loop that gets all table data (used for troubleshooting purposes)
        /*
        System.out.println("Display all results:");
        while(rs.next()){
          int theInt= rs.getInt("autoid");
          int accAva= rs.getInt("available");
          int accNum= rs.getInt("number");
          System.out.println("\tautoid= " + theInt+ "\tAccount Available = " + accAva + "\tAccount Number" + accNum);
        }//end while loop
        */
        
        //While loop that analyzes each row
        while((rs.next())&&(accountVerified!=true))
        {
        		int autoId= rs.getInt("autoid");//gets rows autoid
          		int accAva= rs.getInt("available");//gets the account availability number (0=Available or 1=Not Available)
          		int accNum= rs.getInt("number");//gets the account number that is passed
        		
          		//checks if the account is available
                if(accAva==0)
                {
                	stmt = con.createStatement();
                	stmt.executeUpdate("UPDATE `DBNAME`.`accounts` SET `available` = '1' WHERE `accounts`.`autoid` ="+autoId+" LIMIT 1 ;");
                	accountNumber=accNum;
                    accountVerified=true;
                }
                else
                {
                    accountVerified=false;
                }
        }
        if(accountVerified==false)
        {
            JOptionPane.showMessageDialog(null, "Sorry there are no steam accounts accessible at the moment.");
            System.exit(0);
        }
        else
        {

        	SteamSetter(accountNumber);
            String cmd = "C:\\Program Files\\Program\\program.exe -login ACCOUNT"+accountNumber+" PASSWORD";
            Runtime run = Runtime.getRuntime();
            Process proc = run.exec(cmd);
            
        }

    }
    public void SteamSetter(int accountNumber) throws IOException
    {
        String accountFile="C:\\accountNumber.txt";
        FileWriter fstream = new FileWriter(accountFile);
        BufferedWriter out = new BufferedWriter(fstream);
        out.write(""+accountNumber);
        out.close();
    }
    public void SteamRefresher()throws IOException
    {
    	File accountFile=new File("C:\\accountNumber.txt");
    	accountFile.delete();
    }
}

Here is the program that runs when a user logs off, this program resets the account on the MySQL server based on the account number in the text file then deletes the text file:

/**
 * This is part of the smart login system for steam.
 * This program is initialized by CafeSuite when the user logs off. This gets the
 * account number that the customer was user and sets it back to useable.
 */
import javax.swing.*; //Used for JOption Panes

import java.sql.Statement;// Statement class
import java.io.*;
import java.sql.Connection;//MySQL connection Initiate
import java.sql.DriverManager;//Driver manager
import java.sql.SQLException;//SQLexception class
import java.sql.ResultSet;


public class SteamReset
{
    public SteamReset() throws IOException, SQLException 
    {
    	Statement stmt = null;//This creates a statement variable
    	Connection con = null; //Connection variable
    	ResultSet rs;// result set variable
    	int accountNumber=0;
    	
    	String accountFile="C:\\accountNumber.txt";
        FileReader freader = new FileReader(accountFile);
        BufferedReader inputFile = new BufferedReader(freader);
        
    	String getAccountNumber = inputFile.readLine();
    	SteamRefresher();
        if(getAccountNumber!=null){
        	accountNumber=Integer.parseInt(getAccountNumber);
        }
        else
        {
        	JOptionPane.showMessageDialog(null, "Error: Could not retrieve account");
        	System.exit(0);
        }
    	//tries to connect to the database.
    	try {
    	      Class.forName("com.mysql.jdbc.Driver").newInstance();
    	      con = DriverManager.getConnection("jdbc:mysql://IP ADDRESS:3306/databaseName", "USERNAME", "LOGIN");

    	      //TESTING START
    	      stmt = con.createStatement();
    	      stmt.executeUpdate("UPDATE `databaseName`.`accounts` SET `available` = '0' WHERE `accounts`.`number` ="+accountNumber+" LIMIT 1 ;");
    	      
    	      //TESTING FINISH

    	    } catch(Exception e) {
    	      System.out.println("Exception: " + e.getMessage());
    	    }
    	    
    }
    public void SteamRefresher()throws IOException
    {
    	File file = new File("C:\\accountNumber.txt");
		file.delete();
    }
}

The when the program runs if the text file still exist it shows that that account has not been freed yet, so it will free that account before it retrieves another one. (which I havn't added yet)

Thanks PO

You need to close BufferedReader and FileReader before you attempt to do something with that file. One of many rules, close anything opened as soon you not need it!

You need to close BufferedReader and FileReader before you attempt to do something with that file. One of many rules, close anything opened as soon you not need it!

Thanks peter_budo!

Those small mistakes are the killers! :twisted:

You not out of woods...
Let us know if you still have some problems.

Haha I am working around a logical issue.
The cafe software we use gives us the ability to launch a program at the beginning of a session and the end of the session.

The problem is if the user does a Hard power off or turns the power to the computer off the program doesn't run and deepfreeze erases the text file /w the account number :P

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.