Link to home
Start Free TrialLog in
Avatar of sitijaafar
sitijaafarFlag for Malaysia

asked on

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

Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Try calling File.createTempFile and call deleteOnExit on it
Avatar of sitijaafar

ASKER

Where should I use it?
You need to use it where you're currently creating the file(s) you want to delete
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

I already calling File.createTempFile and call deleteOnExit on it but still cannot delete the file.
Right now can delete the .sql file but txt still can't delete
Are you doing the same with each file? Please post your current code
SOLUTION
Avatar of Venabili
Venabili
Flag of Bulgaria image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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

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.
I already remove FileInputStream fis = new FileInputStream(path2); but still cannot delete the file
It is still in the code that you just posted.
So can you post the code you  run now?
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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

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

Close zip_fi (see my comment just before the latest code)
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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
Great solution :)
sitijaafar, for the benefit of future visitors to this question, can you please post the working version of your code?