Java Code Examples for java.io.File.delete()

The following are Jave code examples for showing how to use delete() of the java.io.File class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: 19porn   File: AHttp.java   View Source Code Vote up 7 votes
public boolean deleteCache(String urlPath){
	String filePathMd5 = stringToMD5(urlPath);
	if(filePathMd5 == null){
		return false;
	}
	
	if(mCacheFileDir == null){
		mCacheFileDir = Environment.getExternalStorageDirectory().toString() + "/ahttp/";
	}
	
	File fileDir = new File(mCacheFileDir);
	if(!fileDir.isDirectory() || !fileDir.exists()){
		return false;
	}
	
	filePathMd5 = mCacheFileDir + filePathMd5 + ".data";
	File file = new File(filePathMd5);
	if(file.exists()){
		file.delete();
	}
	
	return true;
}
 
Example 2
Project: EsperantoRadio   File: Diverse.java   View Source Code Vote up 6 votes
public static int sletFilerÆldreEnd(File mappe, long tidsstempel) {
  int antalByteDerBlevSlettet = 0;
  int antalFilerDerBlevSlettet = 0;
  File[] files = mappe.listFiles();
  if (files != null) {
    for (File file : files) {
      if (file.lastModified() < tidsstempel) {
        antalByteDerBlevSlettet += file.length();
        antalFilerDerBlevSlettet++;
        file.delete();
      }
    }
  }
  Log.d("sletFilerÆldreEnd: " + mappe.getName() + ": " + antalFilerDerBlevSlettet + " filer blev slettet, og " + antalByteDerBlevSlettet / 1000 + " kb frigivet");
  return antalByteDerBlevSlettet;
}
 
Example 3
Project: OpenJSharp   File: FileHandler.java   View Source Code Vote up 6 votes
/**
 * Rotate the set of output files
 */
private synchronized void rotate() {
    Level oldLevel = getLevel();
    setLevel(Level.OFF);

    super.close();
    for (int i = count-2; i >= 0; i--) {
        File f1 = files[i];
        File f2 = files[i+1];
        if (f1.exists()) {
            if (f2.exists()) {
                f2.delete();
            }
            f1.renameTo(f2);
        }
    }
    try {
        open(files[0], false);
    } catch (IOException ix) {
        // We don't want to throw an exception here, but we
        // report the exception to any registered ErrorManager.
        reportError(null, ix, ErrorManager.OPEN_FAILURE);

    }
    setLevel(oldLevel);
}
 
Example 4
Project: filestack-java   File: TestFileLink.java   View Source Code Vote up 6 votes
@Test
public void testDownloadCustomFilename() throws Exception {
  Mockito
      .doReturn(Helpers.createRawCall("text/plain", "Test content"))
      .when(Networking.getCdnService())
      .get("handle", null, null);

  Config config = new Config("apikey");
  FileLink fileLink = new FileLink(config, "handle");

  File file = fileLink.download("/tmp/", "filestack_test_filelink_download.txt");
  Assert.assertTrue(file.isFile());
  if (!file.delete()) {
    Assert.fail("Unable to cleanup resource");
  }
}
 
Example 5
Project: q-mail   File: MigrationTo51.java   View Source Code Vote up 6 votes
private static void cleanUpOldAttachmentDirectory(File attachmentDirOld) {
    if (!attachmentDirOld.exists()) {
        Timber.d("Old attachment directory doesn't exist: %s", attachmentDirOld.getAbsolutePath());
        return;
    }
    for (File file : attachmentDirOld.listFiles()) {
        Timber.d("deleting stale attachment file: %s", file.getName());
        if (file.exists() && !file.delete()) {
            Timber.d("Failed to delete stale attachement file: %s", file.getAbsolutePath());
        }
    }

    Timber.d("deleting old attachment directory");
    if (attachmentDirOld.exists() && !attachmentDirOld.delete()) {
        Timber.d("Failed to delete old attachement directory: %s", attachmentDirOld.getAbsolutePath());
    }
}
 
Example 6
Project: guava-mock   File: FileBackedOutputStream.java   View Source Code Vote up 6 votes
/**
 * Calls {@link #close} if not already closed, and then resets this object back to its initial
 * state, for reuse. If data was buffered to a file, it will be deleted.
 *
 * @throws IOException if an I/O error occurred while deleting the file buffer
 */
public synchronized void reset() throws IOException {
  try {
    close();
  } finally {
    if (memory == null) {
      memory = new MemoryOutput();
    } else {
      memory.reset();
    }
    out = memory;
    if (file != null) {
      File deleteMe = file;
      file = null;
      if (!deleteMe.delete()) {
        throw new IOException("Could not delete: " + deleteMe);
      }
    }
  }
}
 
Example 7
Project: easyfilemanager   File: FileUtils.java   View Source Code Vote up 6 votes
public static boolean deleteFile(File file) {
    if (file.exists() && file.isFile() && file.canWrite()) {
        return file.delete();
    } else if (file.isDirectory()) {
        if (null != file && file.list() != null && file.list().length == 0) {
            return file.delete();
        } else {
            String[] fileList = file.list();
            for (String filePaths : fileList) {
                File tempFile = new File(file.getAbsolutePath() + "/" + filePaths);
                if (tempFile.isFile()) {
                    tempFile.delete();
                } else {
                    deleteFile(tempFile);
                    tempFile.delete();
                }
            }

        }
        if (file.exists()) {
            return file.delete();
        }
    }
    return false;
}
 
Example 8
Project: ArtOfAndroid   File: DiskLruCache.java   View Source Code Vote up 6 votes
/**
 * Recursively delete everything in {@code dir}.
 */
// TODO: this should specify paths as Strings rather than as Files
public static void deleteContents(File dir) throws IOException {
    File[] files = dir.listFiles();
    if (files == null) {
        throw new IllegalArgumentException("not a directory: " + dir);
    }
    for (File file : files) {
        if (file.isDirectory()) {
            deleteContents(file);
        }
        if (!file.delete()) {
            throw new IOException("failed to delete file: " + file);
        }
    }
}
 
Example 9
Project: buildAPKsSamples   File: Utils.java   View Source Code Vote up 6 votes
public static void cleanCache(Context c) {		
	File[] list = getCacheDir(c).listFiles(new FilenameFilter(){

		@Override
		public boolean accept(File dir, String filename) {
			return filename.toLowerCase().endsWith(".jpg");
		}});
	
	long t = System.currentTimeMillis();
	for (File f: list) {			
		if (f.lastModified() < t - CLEAN_TIME ||
				t + CLEAN_TIME < f.lastModified()) {
			SendReduced.log("cleaning up "+f);
			f.delete();
		}
	}
}
 
Example 10
Project: boohee_v5.6   File: MultiDexExtractor.java   View Source Code Vote up 6 votes
private static void prepareDexDir(File dexDir, final String extractedFilePrefix) throws IOException {
    mkdirChecked(dexDir.getParentFile());
    mkdirChecked(dexDir);
    File[] files = dexDir.listFiles(new FileFilter() {
        public boolean accept(File pathname) {
            return !pathname.getName().startsWith(extractedFilePrefix);
        }
    });
    if (files == null) {
        Log.w(TAG, "Failed to list secondary dex dir content (" + dexDir.getPath() + ").");
        return;
    }
    for (File oldFile : files) {
        Log.i(TAG, "Trying to delete old file " + oldFile.getPath() + " of size " + oldFile.length());
        if (oldFile.delete()) {
            Log.i(TAG, "Deleted old file " + oldFile.getPath());
        } else {
            Log.w(TAG, "Failed to delete old file " + oldFile.getPath());
        }
    }
}
 
Example 11
Project: monarch   File: JarDeployerDUnitTest.java   View Source Code Vote up 6 votes
void releaseLock(final FileLock fileLock, final File lockFile) throws IOException {
  if (lockFile == null) {
    return;
  }

  try {
    if (fileLock != null) {
      fileLock.release();
      fileLock.channel().close();
    }
  } finally {
    if (!lockFile.delete()) {
      lockFile.deleteOnExit();
    }
  }
}
 
Example 12
Project: Rey-MusicPlayer   File: FileUtils.java   View Source Code Vote up 6 votes
public static boolean deleteFile(File file) {
    if (file == null) {
        throw new NullPointerException("File can't be null");
    }
    if (MusicUtils.isFromSdCard(file.getAbsolutePath())) {
        DocumentFile documentFile = getDocumentFile(file);
        if (documentFile.isDirectory()) {
            deleteDirectory(documentFile);
        } else {
            Logger.log("Deleted File Name  " + file.getName());
            return documentFile.delete();
        }
    } else {
        return file.delete();
    }
    return false;
}
 
Example 13
Project: monarch   File: LocatorJUnitTest.java   View Source Code Vote up 5 votes
@Before
public void setUp() throws IOException {
  tmpFile = File.createTempFile("locator", ".log");
  this.port = portSupplier.getAsInt();
  File locatorFile = new File("locator" + this.port + ".dat");
  if (locatorFile.exists()) {
    locatorFile.delete();
  }
}
 
Example 14
Project: RefDiff   File: FrontEnd.java   View Source Code Vote up 5 votes
private void deleteDirectory(File dir) {
    if (dir.isDirectory()) {
        File[] children = dir.listFiles();
        for (int i = 0; i < children.length; i++) {
            deleteDirectory(children[i]);
        }
    }  
    dir.delete();
}
 
Example 15
Project: oscm   File: InitializerTest.java   View Source Code Vote up 5 votes
@SuppressWarnings("boxing")
@Test
public void testLoggingWithFileAccessException() throws Exception {
    File log4jFile = createLog4jFile(LOG4J_CONFIG1);
    try {
        // Set path of log4j properties
        log4jFolderPath = log4jFile.getParentFile().getParent();
        setSysSetting(log4jFolderPath);

        // Invoke "private" method :)
        Method method = testElm.getClass().getDeclaredMethod(
                "postConstruct");
        method.setAccessible(true);
        method.invoke(testElm);

        // Now we exchange the internal stored file with a mockup :)
        File oopsFile = Mockito.mock(File.class);
        Field fileField = testElm.getClass().getDeclaredField("logFile");
        fileField.setAccessible(true);
        fileField.set(testElm, oopsFile);

        // And enable damage!
        Mockito.when(oopsFile.lastModified()).thenThrow(
                new SecurityException());

        // Simulate timer (-> this will now result in a security exception!)
        testElm.handleTimer(null);

        // Simulate timer (-> this will now result in a security exception!)
        testElm.handleTimer(null);

    } finally {
        log4jFile.delete();
        resetSysSetting();
    }

}
 
Example 16
Project: picocli   File: CommandLineTest.java   View Source Code Vote up 5 votes
@Test
public void testRecursiveNestedAtFileIgnored() throws IOException {
    class App {
        @Option(names = "-x")
        private boolean xxx;

        @Option(names = "-f")
        private String[] fff;

        @Option(names = "-v")
        private boolean verbose;

        @Parameters
        private List<String> files;
    }
    File file = findFile("/argfile-with-recursive-at-file.txt");
    File localCopy = new File("argfile-with-recursive-at-file.txt");
    localCopy.delete();
    assertFalse("does not exist yet", localCopy.exists());
    copyFile(file, localCopy);

    setTraceLevel("OFF");
    App app = new App();
    CommandLine commandLine = new CommandLine(app).setOverwrittenOptionsAllowed(true);
    commandLine.parse("-f", "fVal1", "@" + localCopy.getAbsolutePath(),  "-f", "fVal2");
    assertEquals(Arrays.asList("abc defg", "xyz"), app.files);
    assertArrayEquals(new String[]{"fVal1", "fVal2"}, app.fff);
    assertFalse("not invoked", app.verbose);
    assertFalse("not invoked", app.xxx);
    assertTrue("Deleted " + localCopy, localCopy.delete());
}
 
Example 17
Project: ZooKeeper   File: LearnerTest.java   View Source Code Vote up 5 votes
static private void recursiveDelete(File dir) {
	if (dir == null || !dir.exists()) {
		return;
	}
	if (!dir.isDirectory()) {
		dir.delete();
	}
	for(File child: dir.listFiles()) {
		recursiveDelete(child);
	}
}
 
Example 18
Project: dswork   File: FileUtil.java   View Source Code Vote up 5 votes
/**
 * 删除
 * @param filePath 删除的文件夹或文件名称(全路径)
 * @param isDeleteDir 是否删除自己(删除对象为文件夹时有效),值为false时isDeleteSubDir和isKeepStructure参数有效
 * @param isDeleteSubDir 是否删除子文件夹,false时仅删除当前目录下的文件,值为true是isKeepStructure参数有效
 * @param isKeepStructure 是否保留子文件夹的目录结构
 * @return boolean
 */
public static boolean delete(String filePath, boolean isDeleteDir, boolean isDeleteSubDir, boolean isKeepStructure)
{
	try
	{
		boolean success = true;
		File file = new File(filePath);
		if(file.isDirectory())
		{
			String[] children = file.list();
			for(int i = 0; i < children.length; i++)
			{
				File subFile = new File(file, children[i]);
				if(isDeleteDir || subFile.isFile())
				{
					success = delete(subFile.getPath(), true, true, false) && success;
				}
				else if(isDeleteSubDir)// 是否删除子目录
				{
					success = delete(subFile.getPath(), !isKeepStructure, true, isKeepStructure) && success;
				}
			}
			if(isDeleteDir)
			{
				success = file.delete() && success;// 删除该空目录
			}
		}
		else if(file.isFile())
		{
			success = file.delete() && success;// 删除该文件
		}
		return success;
	}
	catch(Exception e)
	{
		return false;
	}
}
 
Example 19
Project: StackNet   File: H2ODeepLearningClassifier.java   View Source Code Vote up 4 votes
@Override
public double[] predict(double[][] data) {
	
	File directory = new File(this.usedir +  File.separator +  "models");
	if (! directory.exists()){
		directory.mkdir();
	}
	
	/*
	 *  check if the Create_Logic method is run properly
	 */
	if (n_classes<2 ||new File(this.usedir +  File.separator +  "models"+File.separator + this.model_name +".mod").exists()==false ){
		 throw new IllegalStateException("The fit method needs to be run successfully in " +
									"order to create the logic before attempting scoring a new set");}   

	if (data==null || data.length<=0){
		throw new IllegalStateException(" There is nothing to score" );
	}
	if (data[0].length!=columndimension){
		throw new IllegalStateException(" Number of predictors is not the same as th4 trained one: " +  columndimension + " <> " + data[0].length);	
	}		
	if (this.threads<=0){
		this.threads=Runtime.getRuntime().availableProcessors();
		if (this.threads<1){
			this.threads=1;
		}
	}	
	
	smatrix X= new smatrix(data);
	output out = new output();
	out.verbose=false;
	out.printsmatrix(X,new double [X.GetRowDimension()],this.usedir +  File.separator +  "models"+File.separator + this.model_name + ".test");//this.usedir +  File.separator +  "models"+File.separator + 
	X=null;

	System.gc();
	
	double predictions[]= new double [data.length];
	double prediction_probas[][]=this.create_h2o_cluster_predict(this.usedir +  File.separator +  "models"+File.separator + this.model_name + ".test", this.usedir +  File.separator +  "models"+File.separator + this.model_name +".mod"); 
	double temp[]=null;
       // create new file
	File f = new File(this.usedir +  File.separator +  "models"+File.separator + this.model_name + ".test" );
       f.delete();    
	System.gc();
		// return the 1st prediction

	for (int i=0; i < predictions.length; i++) {
		 temp=prediction_probas[i];
    	  int maxi=0;
    	  double max=temp[0];
    	  for (int k=1; k<n_classes; k++) {
    		 if (temp[k]>max){
    			 max=temp[k];
    			 maxi=k;	 
    		 }
    	  }
    	  try{
    		  predictions[i]=Double.parseDouble(classes[maxi]);
    	  } catch (Exception e){
    		  predictions[i]=maxi;
    	  }

	}		
	
	prediction_probas=null;

		// return the 1st prediction
		return predictions;


		
		}
 
Example 20
Project: SigFW   File: SS7Server.java   View Source Code Vote up 4 votes
/**
 * @param args
 */
public static void main(String[] args) {
    logger.debug("*************************************");
    logger.debug("***           SS7Server           ***");
    logger.debug("*************************************");
    
    // clear XML dir
    File index = new File(persistDir);
    if (!index.exists()) {
        index.mkdir();
    } else {
        String[]entries = index.list();
        for(String s: entries){
            File currentFile = new File(index.getPath(),s);
            currentFile.delete();
        }
    }
    //
    
    IpChannelType ipChannelType = IpChannelType.SCTP;
    if (args.length >= 1 && args[0].toLowerCase().equals("tcp")) {
        ipChannelType = IpChannelType.TCP;
    }

    logger.setLevel(org.apache.log4j.Level.DEBUG);
    
    final SS7Server server = new SS7Server();
    try {
        server.initializeStack(ipChannelType);
    } catch (Exception e) {
        e.printStackTrace();
    }
    
    try {
        while (true) {
            if(server.serverM3UAMgmt.isStarted() == true) {
                for (As a : server.serverM3UAMgmt.getAppServers()) {
                    if (a.isConnected() && a.isUp()) {
                        //server.initiateUSSD();
                    }
                }
                
            } else {
                //server.serverM3UAMgmt.start();
            }
            
            Thread.sleep(1000);
        }
    } catch (Exception ex) {
        java.util.logging.Logger.getLogger(SS7Server.class.getName()).log(Level.SEVERE, null, ex);
    }
    
}