Cannot delete a file

In this code I create 3 file .txt,.sql and .zip file.  After finish zip the file I want to delete the .txt and .sql file.  But cannot, I also try delete it manually but it give a message said that the file being used by another person or program.  Actually what wrong with my code:
StringBuffer qbuffer = new StringBuffer();
								
	path1=file.getParent()+ "\\" + tableName+".sql"; 	
	path2=file.getParent()+ "\\" + tableName+".txt"; 				
															
	qBuffer.append("bcp \"SELECT * from "+ dbName + ".dbo.audit_trail ");
if(alData.getFromDate()!=null){
	Timestamp FromDate = new Timestamp(alData.getFromDate().getTime());
	String from = FromDate.toString();
	qBuffer.append("WHERE access_time >='"+from+"' ");
	if (log.isDebugEnabled())									
		log.debug("from date"+from);									
	}
									
if(alData.getToDate()!=null){
	Calendar tempCal = Calendar.getInstance();
	tempCal.setTime(alData.getToDate());
	tempCal.add(Calendar.DATE, 1);
	Timestamp ToDate = new Timestamp(tempCal.getTime().getTime());
	String to = ToDate.toString();
	qBuffer.append("AND access_time <'"+to+"' ");
	if (log.isDebugEnabled())									
	log.debug("from to"+to);
	}
									
qBuffer.append("\" queryout \""+ path2 + "\" -c -S " + dbHost +" -U "+ dbUsername + " -P " + dbPassword);
								

	execStr =qBuffer.toString();
									
	if (log.isInfoEnabled())
		log.info("bcp execstr = "+execStr);
								
	Runtime runtime = Runtime.getRuntime();
	Process child = runtime.exec(execStr);
								
	InputStream stdin = child.getInputStream();
	InputStreamReader isr = new InputStreamReader(stdin);
	BufferedReader brs = new BufferedReader(isr);
	String lines = null; 
					    	    
	if (log.isDebugEnabled())
		log.debug("bcp <OUTPUT> ");			
			    					 	
	while ( (lines = brs.readLine()) != null) 
	{
		if (log.isDebugEnabled())
				  log.debug(lines);				    	    
			}
					    	    
	if (log.isDebugEnabled())
		log.debug("bcp <OUTPUT> ");	
					    	    
	int exitCode = child.waitFor();
					    	    
								
	writer = new BufferedWriter(new FileWriter(path1));
	FileInputStream fis = new FileInputStream(path2);
								
	writer = new BufferedWriter(new FileWriter(file));						        
	irs = new InputStreamReader(child.getInputStream());
	br = new BufferedReader(irs);
						        
	String line;
	while( (line=br.readLine()) != null ) {
		writer.write(line + "\n");
		}
						        
	writer.close()
	irs.close();
	br.close();		
						        
	if (log.isDebugEnabled())
	{
		log.debug("zip filename - "+file.getAbsolutePath()+".zip");
		log.debug("zip filename - "+file.getParent() + "//" + tableName +".zip");
		log.debug("zip filename getName - "+file.getName());
		}
// Compressing the archived file
	zip_dest = new FileOutputStream(file.getParent() + "//" + tableName +".zip");
	zip_out = new ZipOutputStream(new BufferedOutputStream(zip_dest));
	byte zipdata[] = new byte[BUFFER];
	zip_fi = new FileInputStream(path2);
	zip_origin = new BufferedInputStream(zip_fi, BUFFER);
	ZipEntry entry = new ZipEntry(file.getName());
								
		if (log.isDebugEnabled())
			log.debug("zipped source filename - "+file.getAbsolutePath());
								
		zip_out.putNextEntry(entry);
		int count;
		while((count = zip_origin.read(zipdata, 0,BUFFER)) != -1) {
			zip_out.write(zipdata, 0, count);
				}
						       
						        
		zip_origin.close();
		zip_out.close();
						        
	String path=file.getAbsolutePath();
						   
	String txtFileName="";
	String txtFilePath="";								
	txtFileName = path.substring(0, path.indexOf(".sql"));
	txtFilePath=txtFileName+".txt";
	if (log.isDebugEnabled())
	{
		log.debug("txtFilePath "+txtFilePath);									
											
	}
	boolean deleteSqlFile = file.delete();
	File file2 = new File(txtFilePath);									
									
	boolean deleteTxtFile =file2.delete();
	if (log.isDebugEnabled())
	{
		log.debug("deleteSqlFile - "+deleteSqlFile);
		log.debug("deleteTxtFile - "+deleteTxtFile);
												
										
}
						        	
		}

Open in new window

sitijaafarAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

CEHJCommented:
Try calling File.createTempFile and call deleteOnExit on it
0
sitijaafarAuthor Commented:
Where should I use it?
0
CEHJCommented:
You need to use it where you're currently creating the file(s) you want to delete
0
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

CEHJCommented:
You'd have something like:
	File temp1 = File.createTempFile(file.getParent(), tableName+".sql");        
	temp1.deleteOnExit();
	....
	writer = new BufferedWriter(new FileWriter(temp1));

Open in new window

0
sitijaafarAuthor Commented:
I already calling File.createTempFile and call deleteOnExit on it but still cannot delete the file.
0
sitijaafarAuthor Commented:
Right now can delete the .sql file but txt still can't delete
0
CEHJCommented:
Are you doing the same with each file? Please post your current code
0
VenabiliCommented:
You have
FileInputStream fis = new FileInputStream(path2);
which is opening a stream to the .txt file and you never use or close it.

So either close it OR just remove the line if you do not need it and you should be able to delete the file.
0
sitijaafarAuthor Commented:
Ok here is my code:
private void archiveMercAudit(HttpServletRequest req, HttpServletResponse res,  Connection auditConn, Connection 

adminConn) throws Exception {
				
try {
	AdminDB adb = new AdminDB();
	ArchiveAuditTrailManager archiveMerc = new ArchiveAuditTrailManager();
			
	AuditLogDetails audit = getSearchAuditLogParameter(req,adminConn);
			
	boolean bPurge = false;

	String arcName = adb.getTableName(audit,auditConn);

		if(log.isDebugEnabled())
			log.debug("Filename = " + arcName);
						
	// create temp file
	File archPath = new File(System.getProperty("archive_path"));
        File file = File.createTempFile(arcName + "_", ".sql", archPath);
        file.deleteOnExit();
        File file2 = File.createTempFile(arcName + "_", ".txt", archPath);
        file2.deleteOnExit();

	int iResult = archiveMerc.zipMercLogToFile(req, file,file2,audit);
								
								
								
	if(log.isDebugEnabled())
	{
		log.debug("iResult = " + iResult);
	}


	boolean deleteSqlFile = file.delete();									
																

				
	boolean deleteTxtFile =file2.delete();	

} catch (Exception e) {
			log.error("function = archiveMercAudit(); desc = "+e);
			throw e;
		}		
	}


////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////

public int zipMercLogToFile(HttpServletRequest req, File file,File file2, AuditLogDetails alData) throws Exception{
		
	BufferedWriter writer = null;
	InputStreamReader irs = null;
	BufferedReader br = null;
	Connection conn = null;		
	PreparedStatement p = null;
	ResultSet rs=null;
        BufferedInputStream zip_origin = null;
        FileOutputStream zip_dest = null;
        ZipOutputStream zip_out = null;
	FileInputStream zip_fi = null;		
	int iResult=0;
		
	try{
			
		String tableName = ""; // "audit_trail_backup";
		String username = "";
		String access_time = "";
		String path1="";	
		String path2="";
		int status_code = 0;
		int did = 0;
		String IP = "";
		Long ipint = 0L;
		StringBuffer qBuffer = new StringBuffer();
		AdminDB adb = new AdminDB();		
		
		
			
		if(file!=null)
		{
			tableName = file.getName();
				
			if(tableName.endsWith(".sql"))
				{
				tableName = tableName.substring(0, tableName.length()-4);
					
				if (log.isDebugEnabled())
					log.debug("tableName = "+tableName);
					
					
				conn = DBConnection.getConnection();
						
	HttpSession session=req.getSession();
	String merchantName = !ErrorChecking.getString(req, "merchant_name").equals("")
												? 	

ErrorChecking.getString(req, "merchant_name")
												: !	

ErrorChecking.getString(session, "merchant_name").equals("")
														? 	

ErrorChecking.getString(session, "merchant_name")
													: "";

	boolean isDefault=merchantName.trim().equals("")?true:false;
	String query="select * from merchant_resource "+(isDefault?"":" where merchantID=?");
	p=conn.prepareStatement(query);
						
	if(!isDefault)
	p.setBytes(1, merchantName.getBytes("UTF8"));
						
	rs=p.executeQuery();
	String dbUsername="";
	String dbPassword="";
	String dbUrl="";
	String dbHost="";
	String dbPort="";
	String dbName="";
	String execStr="";

	if(rs.next()){
		dbUsername=rs.getString("audituserid");
		dbPassword=rs.getString("auditpassword");
		dbUrl=rs.getString("auditurl");
		dbUrl = dbUrl.substring(dbUrl.indexOf("//")+2);}

	dbUrl = dbUrl.substring(0,dbUrl.lastIndexOf(';'));					
	dbHost = dbUrl.substring(0,dbUrl.indexOf(":"));					
	dbPort = dbUrl.substring(dbUrl.indexOf(":")+1,dbUrl.indexOf(";"));					
	dbName = dbUrl.substring(dbUrl.indexOf("=")+1);
	dbName = dbName.substring(0,dbName.indexOf(";"));	



StringBuffer qbuffer = new StringBuffer();
								
	path1=file.getParent()+ "\\" + tableName+".sql"; 	
	path2=file2.getParent()+ "\\" + tableName+".txt"; 				
															
	qBuffer.append("bcp \"SELECT * from "+ dbName + ".dbo.audit_trail ");
if(alData.getFromDate()!=null){
	Timestamp FromDate = new Timestamp(alData.getFromDate().getTime());
	String from = FromDate.toString();
	qBuffer.append("WHERE access_time >='"+from+"' ");
	if (log.isDebugEnabled())									
		log.debug("from date"+from);									
	}
									
if(alData.getToDate()!=null){
	Calendar tempCal = Calendar.getInstance();
	tempCal.setTime(alData.getToDate());
	tempCal.add(Calendar.DATE, 1);
	Timestamp ToDate = new Timestamp(tempCal.getTime().getTime());
	String to = ToDate.toString();
	qBuffer.append("AND access_time <'"+to+"' ");
	if (log.isDebugEnabled())									
	log.debug("from to"+to);
	}
									
qBuffer.append("\" queryout \""+ path2 + "\" -c -S " + dbHost +" -U "+ dbUsername + " -P " + dbPassword);
								

	execStr =qBuffer.toString();
									
	if (log.isInfoEnabled())
		log.info("bcp execstr = "+execStr);
								
	Runtime runtime = Runtime.getRuntime();
	Process child = runtime.exec(execStr);
								
	InputStream stdin = child.getInputStream();
	InputStreamReader isr = new InputStreamReader(stdin);
	BufferedReader brs = new BufferedReader(isr);
	String lines = null; 
					    	    
	if (log.isDebugEnabled())
		log.debug("bcp <OUTPUT> ");			
			    					 	
	while ( (lines = brs.readLine()) != null) 
	{
		if (log.isDebugEnabled())
				  log.debug(lines);				    	    
			}
					    	    
	if (log.isDebugEnabled())
		log.debug("bcp <OUTPUT> ");	
					    	    
	int exitCode = child.waitFor();
					    	    
								
	writer = new BufferedWriter(new FileWriter(path1));
	FileInputStream fis = new FileInputStream(path2);
								
	writer = new BufferedWriter(new FileWriter(file));						        
	irs = new InputStreamReader(child.getInputStream());
	br = new BufferedReader(irs);
						        
	String line;
	while( (line=br.readLine()) != null ) {
		writer.write(line + "\n");
		}
						        
	writer.close()
	irs.close();
	br.close();		
						        
	if (log.isDebugEnabled())
	{
		log.debug("zip filename - "+file.getAbsolutePath()+".zip");
		log.debug("zip filename - "+file.getParent() + "//" + tableName +".zip");
		log.debug("zip filename getName - "+file.getName());
		}
// Compressing the archived file
	zip_dest = new FileOutputStream(file.getParent() + "//" + tableName +".zip");
	zip_out = new ZipOutputStream(new BufferedOutputStream(zip_dest));
	byte zipdata[] = new byte[BUFFER];
	zip_fi = new FileInputStream(path2);
	zip_origin = new BufferedInputStream(zip_fi, BUFFER);
	ZipEntry entry = new ZipEntry(file.getName());
								
		if (log.isDebugEnabled())
			log.debug("zipped source filename - "+file.getAbsolutePath());
								
		zip_out.putNextEntry(entry);
		int count;
		while((count = zip_origin.read(zipdata, 0,BUFFER)) != -1) {
			zip_out.write(zipdata, 0, count);
				}
						       
						        
		zip_origin.close();
		zip_out.close();
}										        
			}
		p.close();
		rs.close();

} catch (IOException ex) {
			log.error("function zipMercLogToFile(), exception = " + ex);
	        throw ex;
	    } finally{
	    	if (irs != null) irs.close();
	        if (br != null) br.close();
	        if (writer != null) writer.close();
			if (p!=null) p.close();
			if (rs!=null) rs.close();
			if (conn!=null) conn.close();
			if (zip_origin!=null) zip_origin.close();
			if (zip_out !=null) zip_out.close();			
		}
	    
	    return iResult;
	}	
						        
										        
	

Open in new window

0
VenabiliCommented:
Again:
Either remove
FileInputStream fis = new FileInputStream(path2);
or close it. As you do not use it, I would simply remove it but if you want it there, just make sure you close it.
0
sitijaafarAuthor Commented:
I already remove FileInputStream fis = new FileInputStream(path2); but still cannot delete the file
0
VenabiliCommented:
It is still in the code that you just posted.
So can you post the code you  run now?
0
VenabiliCommented:
And you also have
zip_fi = new FileInputStream(path2);

But you never close zip_fi either. So close this one also :)
0
sitijaafarAuthor Commented:
the new code
private void archiveMercAudit(HttpServletRequest req, HttpServletResponse res,  Connection auditConn, Connection 

adminConn) throws Exception {
				
try {
	AdminDB adb = new AdminDB();
	ArchiveAuditTrailManager archiveMerc = new ArchiveAuditTrailManager();
			
	AuditLogDetails audit = getSearchAuditLogParameter(req,adminConn);
			
	boolean bPurge = false;

	String arcName = adb.getTableName(audit,auditConn);

		if(log.isDebugEnabled())
			log.debug("Filename = " + arcName);
						
	// create temp file
	File archPath = new File(System.getProperty("archive_path"));
        File file = File.createTempFile(arcName + "_", ".sql", archPath);
        file.deleteOnExit();
        File file2 = File.createTempFile(arcName + "_", ".txt", archPath);
        file2.deleteOnExit();

	int iResult = archiveMerc.zipMercLogToFile(req, file,file2,audit);
								
								
								
	if(log.isDebugEnabled())
	{
		log.debug("iResult = " + iResult);
	}


	boolean deleteSqlFile = file.delete();									
																

				
	boolean deleteTxtFile =file2.delete();	

} catch (Exception e) {
			log.error("function = archiveMercAudit(); desc = "+e);
			throw e;
		}		
	}


////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////

public int zipMercLogToFile(HttpServletRequest req, File file,File file2, AuditLogDetails alData) throws Exception{
		
	BufferedWriter writer = null;
	InputStreamReader irs = null;
	BufferedReader br = null;
	Connection conn = null;		
	PreparedStatement p = null;
	ResultSet rs=null;
        BufferedInputStream zip_origin = null;
        FileOutputStream zip_dest = null;
        ZipOutputStream zip_out = null;
	FileInputStream zip_fi = null;		
	int iResult=0;
		
	try{
			
		String tableName = ""; // "audit_trail_backup";
		String username = "";
		String access_time = "";
		String path1="";	
		String path2="";
		int status_code = 0;
		int did = 0;
		String IP = "";
		Long ipint = 0L;
		StringBuffer qBuffer = new StringBuffer();
		AdminDB adb = new AdminDB();		
		
		
			
		if(file!=null)
		{
			tableName = file.getName();
				
			if(tableName.endsWith(".sql"))
				{
				tableName = tableName.substring(0, tableName.length()-4);
					
				if (log.isDebugEnabled())
					log.debug("tableName = "+tableName);
					
					
				conn = DBConnection.getConnection();
						
	HttpSession session=req.getSession();
	String merchantName = !ErrorChecking.getString(req, "merchant_name").equals("")
												? 	

ErrorChecking.getString(req, "merchant_name")
												: !	

ErrorChecking.getString(session, "merchant_name").equals("")
														? 	

ErrorChecking.getString(session, "merchant_name")
													: "";

	boolean isDefault=merchantName.trim().equals("")?true:false;
	String query="select * from merchant_resource "+(isDefault?"":" where merchantID=?");
	p=conn.prepareStatement(query);
						
	if(!isDefault)
	p.setBytes(1, merchantName.getBytes("UTF8"));
						
	rs=p.executeQuery();
	String dbUsername="";
	String dbPassword="";
	String dbUrl="";
	String dbHost="";
	String dbPort="";
	String dbName="";
	String execStr="";

	if(rs.next()){
		dbUsername=rs.getString("audituserid");
		dbPassword=rs.getString("auditpassword");
		dbUrl=rs.getString("auditurl");
		dbUrl = dbUrl.substring(dbUrl.indexOf("//")+2);}

	dbUrl = dbUrl.substring(0,dbUrl.lastIndexOf(';'));					
	dbHost = dbUrl.substring(0,dbUrl.indexOf(":"));					
	dbPort = dbUrl.substring(dbUrl.indexOf(":")+1,dbUrl.indexOf(";"));					
	dbName = dbUrl.substring(dbUrl.indexOf("=")+1);
	dbName = dbName.substring(0,dbName.indexOf(";"));	



StringBuffer qbuffer = new StringBuffer();
								
	path1=file.getParent()+ "\\" + tableName+".sql"; 	
	path2=file2.getParent()+ "\\" + tableName+".txt"; 				
															
	qBuffer.append("bcp \"SELECT * from "+ dbName + ".dbo.audit_trail ");
if(alData.getFromDate()!=null){
	Timestamp FromDate = new Timestamp(alData.getFromDate().getTime());
	String from = FromDate.toString();
	qBuffer.append("WHERE access_time >='"+from+"' ");
	if (log.isDebugEnabled())									
		log.debug("from date"+from);									
	}
									
if(alData.getToDate()!=null){
	Calendar tempCal = Calendar.getInstance();
	tempCal.setTime(alData.getToDate());
	tempCal.add(Calendar.DATE, 1);
	Timestamp ToDate = new Timestamp(tempCal.getTime().getTime());
	String to = ToDate.toString();
	qBuffer.append("AND access_time <'"+to+"' ");
	if (log.isDebugEnabled())									
	log.debug("from to"+to);
	}
									
qBuffer.append("\" queryout \""+ path2 + "\" -c -S " + dbHost +" -U "+ dbUsername + " -P " + dbPassword);
								

	execStr =qBuffer.toString();
									
	if (log.isInfoEnabled())
		log.info("bcp execstr = "+execStr);
								
	Runtime runtime = Runtime.getRuntime();
	Process child = runtime.exec(execStr);
								
	InputStream stdin = child.getInputStream();
	InputStreamReader isr = new InputStreamReader(stdin);
	BufferedReader brs = new BufferedReader(isr);
	String lines = null; 
					    	    
	if (log.isDebugEnabled())
		log.debug("bcp <OUTPUT> ");			
			    					 	
	while ( (lines = brs.readLine()) != null) 
	{
		if (log.isDebugEnabled())
				  log.debug(lines);				    	    
			}
					    	    
	if (log.isDebugEnabled())
		log.debug("bcp <OUTPUT> ");	
					    	    
	int exitCode = child.waitFor();
					    	    
							
	
								
	writer = new BufferedWriter(new FileWriter(file));						        
	irs = new InputStreamReader(child.getInputStream());
	br = new BufferedReader(irs);
						        
	String line;
	while( (line=br.readLine()) != null ) {
		writer.write(line + "\n");
		}
						        
	writer.close()
	irs.close();
	br.close();		
						        
	if (log.isDebugEnabled())
	{
		log.debug("zip filename - "+file.getAbsolutePath()+".zip");
		log.debug("zip filename - "+file.getParent() + "//" + tableName +".zip");
		log.debug("zip filename getName - "+file.getName());
		}
// Compressing the archived file
	zip_dest = new FileOutputStream(file.getParent() + "//" + tableName +".zip");
	zip_out = new ZipOutputStream(new BufferedOutputStream(zip_dest));
	byte zipdata[] = new byte[BUFFER];
	zip_fi = new FileInputStream(path2);
	zip_origin = new BufferedInputStream(zip_fi, BUFFER);
	ZipEntry entry = new ZipEntry(file.getName());
								
		if (log.isDebugEnabled())
			log.debug("zipped source filename - "+file.getAbsolutePath());
								
		zip_out.putNextEntry(entry);
		int count;
		while((count = zip_origin.read(zipdata, 0,BUFFER)) != -1) {
			zip_out.write(zipdata, 0, count);
				}
						       
						        
		zip_origin.close();
		zip_out.close();
}										        
			}
		p.close();
		rs.close();

} catch (IOException ex) {
			log.error("function zipMercLogToFile(), exception = " + ex);
	        throw ex;
	    } finally{
	    	if (irs != null) irs.close();
	        if (br != null) br.close();
	        if (writer != null) writer.close();
			if (p!=null) p.close();
			if (rs!=null) rs.close();
			if (conn!=null) conn.close();
			if (zip_origin!=null) zip_origin.close();
			if (zip_out !=null) zip_out.close();			
		}
	    
	    return iResult;
	}

Open in new window

0
CEHJCommented:
You should clean up your code first by ridding it of unnecessary references. If you're chaining streams, all you need is this pattern and use it throughout
InputStream in = new BufferedInputStream(new FileInputStream(x)); // no need for separate ref to the FileInputStream

Open in new window

0
VenabiliCommented:
Close zip_fi (see my comment just before the latest code)
0
avya2kCommented:
There are some reasons why your file is not getting deleted.
Check the following check list:
1. Handles are still open in current program.
    Check current thread where you mention in.close() and out.close() explicitly in finally block
2. Handles are opened from external programs:
    You need to check if any other program which may be external to your program or which is spawned from your program, which may still holding handle of the file.
3. Files created dont have permissions from OS.
    I dont think this would be in your case cause you are creating the files.
4. The zip file program may have completed but still holds the handle of the file or not cleaned up the handles at all.
    you can not release the handles without closing the program/ process which is having the handle of files you want to delete
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
sitijaafarAuthor Commented:
Thank you for all of your guides, finally I can solve it, what I have done, is just close everything that need to close.  :) thanks all
0
sitijaafarAuthor Commented:
Great solution :)
0
CEHJCommented:
sitijaafar, for the benefit of future visitors to this question, can you please post the working version of your code?
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java EE

From novice to tech pro — start learning today.