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

The following examples show how to use java.io.File#delete() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestIOUtilities.java    From java-util with Apache License 2.0 8 votes vote down vote up
public void gzipTransferTest(String encoding) throws Exception {
    File f = File.createTempFile("test", "test");

    // perform test
    URL inUrl = TestIOUtilities.class.getClassLoader().getResource("test.gzip");
    FileInputStream in = new FileInputStream(new File(inUrl.getFile()));
    URLConnection c = mock(URLConnection.class);
    when(c.getInputStream()).thenReturn(in);
    when(c.getContentEncoding()).thenReturn(encoding);
    IOUtilities.transfer(c, f, null);
    IOUtilities.close(in);

    // load actual result
    FileInputStream actualIn = new FileInputStream(f);
    ByteArrayOutputStream actualResult = new ByteArrayOutputStream(8192);
    IOUtilities.transfer(actualIn, actualResult);
    IOUtilities.close(actualIn);
    IOUtilities.close(actualResult);


    // load expected result
    ByteArrayOutputStream expectedResult = getUncompressedByteArray();
    assertArrayEquals(expectedResult.toByteArray(), actualResult.toByteArray());
    f.delete();
}
 
Example 2
Source File: Channel.java    From LunaChat with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * チャンネルの情報を保存したファイルを、削除する。
 * @return 削除したかどうか。
 */
protected boolean remove() {

    // フォルダーの取得
    File folder = new File(
            LunaChat.getDataFolder(), FOLDER_NAME_CHANNELS);
    if ( !folder.exists() ) {
        return false;
    }
    File file = new File(folder, name + ".yml");
    if ( !file.exists() ) {
        return false;
    }

    // ファイルを削除
    return file.delete();
}
 
Example 3
Source File: TestFilterOpNumeric.java    From spork with Apache License 2.0 6 votes vote down vote up
@Test
public void testNestedBinCond() throws Throwable {
    File tmpFile = File.createTempFile("test", "txt");
    PrintStream ps = new PrintStream(new FileOutputStream(tmpFile));
    for(int i = 0; i < LOOP_COUNT; i++) {
        ps.println(i + "\t" + i + "\t1");
    }
    ps.close();
    pig.registerQuery("A=load '"
            + Util.encodeEscape(Util.generateURI(tmpFile.toString(), pig.getPigContext())) + "';");
    String query = "A = foreach A generate (($0 < 10 or $0 < 9)?(($1 >= 5 and $1 >= 4) ? 2: 1) : 0);";
    log.info(query);
    pig.registerQuery(query);
    Iterator<Tuple> it = pig.openIterator("A");
    tmpFile.delete();
    int count =0;
    while(it.hasNext()) {
        Tuple t = it.next();
        Integer first = (Integer)t.get(0);
        count+=first;
        assertTrue(first == 1 || first == 2 || first == 0);

    }
    assertEquals("expected count of 15", 15, count);
}
 
Example 4
Source File: JournalKeeperState.java    From journalkeeper with Apache License 2.0 6 votes vote down vote up
public void init(Path path, List<URI> voters, Set<Integer> partitions, URI preferredLeader) throws IOException {
    Files.createDirectories(path.resolve(USER_STATE_PATH));
    InternalState internalState = new InternalState(new ConfigState(voters), partitions, preferredLeader);
    File lockFile = path.getParent().resolve(path.getFileName() + ".lock").toFile();
    try (RandomAccessFile raf = new RandomAccessFile(lockFile, "rw");
         FileChannel fileChannel = raf.getChannel()) {
        FileLock lock = fileChannel.tryLock();
        if (null == lock) {
            throw new ConcurrentModificationException(
                    String.format(
                            "Some other thread is operating the state files! State: %s.", path.toString()
                    ));
        } else {
            flushInternalState(internalStateFile(path), internalState);
            lock.release();
        }
    } finally {
        lockFile.delete();
    }
}
 
Example 5
Source File: Storage.java    From edx-app-android with Apache License 2.0 6 votes vote down vote up
/**
 * Deletes the physical file identified by given absolute file path.
 * Returns true if delete succeeds or if file does NOT exist, false otherwise.
 * DownloadManager actually deletes the physical file when remove method is called.
 * So, this method might not be required for removing downloads.
 * @param filepath The file to delete
 * @return true if delete succeeds or if file does NOT exist, false otherwise.
 */
private boolean deleteFile(String filepath) {
    try {
        if(filepath != null) {
            File file = new File(filepath);

            if (file.exists()) {
                if (file.delete()) {
                    logger.debug("Deleted: " + file.getPath());
                    return true;
                } else {
                    logger.warn("Delete failed: " + file.getPath());
                }
            } else {
                logger.warn("Delete failed, file does NOT exist: " + file.getPath());
                return true;
            }
        }
    } catch(Exception e) {
        logger.error(e);
    }

    return false;
}
 
Example 6
Source File: TestParquetWriter.java    From parquet-mr with Apache License 2.0 6 votes vote down vote up
@Test
public void testBadWriteSchema() throws IOException {
  final File file = temp.newFile("test.parquet");
  file.delete();

  TestUtils.assertThrows("Should reject a schema with an empty group",
      InvalidSchemaException.class, (Callable<Void>) () -> {
        ExampleParquetWriter.builder(new Path(file.toString()))
            .withType(Types.buildMessage()
                .addField(new GroupType(REQUIRED, "invalid_group"))
                .named("invalid_message"))
            .build();
        return null;
      });

  Assert.assertFalse("Should not create a file when schema is rejected",
      file.exists());
}
 
Example 7
Source File: IOUtil.java    From timecat with Apache License 2.0 5 votes vote down vote up
public static void deleteDirs(String themePath) {
    LinkedList<File> themeLinkedList = new LinkedList<File>();
    File themeDir = new File(themePath);
    if (!themeDir.exists()) {
        return;
    } else if (themeDir.isDirectory()) {
        themeLinkedList.addAll(Arrays.asList(themeDir.listFiles()));
        while (!themeLinkedList.isEmpty()) deleteContent(themeLinkedList.pollLast());
    } else {
        themeDir.delete();
    }
}
 
Example 8
Source File: TestReliableSpoolingFileEventReader.java    From mt-flume with Apache License 2.0 5 votes vote down vote up
@After
public void tearDown() {

  // delete all the files & dirs we created
  File[] files = WORK_DIR.listFiles();
  for (File f : files) {
    if (f.isDirectory()) {
      File[] subDirFiles = f.listFiles();
      for (File sdf : subDirFiles) {
        if (!sdf.delete()) {
          logger.warn("Cannot delete file {}", sdf.getAbsolutePath());
        }
      }
      if (!f.delete()) {
        logger.warn("Cannot delete directory {}", f.getAbsolutePath());
      }
    } else {
      if (!f.delete()) {
        logger.warn("Cannot delete file {}", f.getAbsolutePath());
      }
    }
  }
  if (!WORK_DIR.delete()) {
    logger.warn("Cannot delete work directory {}", WORK_DIR.getAbsolutePath());
  }

}
 
Example 9
Source File: FlakySuiteResultTest.java    From flaky-test-handler-plugin with Apache License 2.0 5 votes vote down vote up
public void testSuiteStdioTrimming() throws Exception {
  File data = File.createTempFile("testSuiteStdioTrimming", ".xml");
  try {
    Writer w = new FileWriter(data);
    try {
      PrintWriter pw = new PrintWriter(w);
      pw.println("<testsuites name='x'>");
      pw.println("<testsuite failures='0' errors='0' tests='1' name='x'>");
      pw.println("<testcase name='x' classname='x'/>");
      pw.println("<system-out/>");
      pw.print("<system-err><![CDATA[");
      pw.println("First line is intact.");
      for (int i = 0; i < 100; i++) {
        pw.println("Line #" + i + " might be elided.");
      }
      pw.println("Last line is intact.");
      pw.println("]]></system-err>");
      pw.println("</testsuite>");
      pw.println("</testsuites>");
      pw.flush();
    } finally {
      w.close();
    }
    FlakySuiteResult sr = parseOne(data);
    assertEquals(sr.getStderr(), 1030, sr.getStderr().length());
  } finally {
    data.delete();
  }
}
 
Example 10
Source File: RestDumpActionTest.java    From elasticsearch-inout-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * The 'force_overwrite' parameter forces existing files to be overwritten.
 */
@Test
public void testForceOverwrite() {

    // make sure target directory exists and is empty
    File dumpDir = new File("/tmp/forceDump");
    if (dumpDir.exists()) {
        for (File c : dumpDir.listFiles()) {
            c.delete();
        }
        dumpDir.delete();
    }
    dumpDir.mkdir();

    // initial dump to target directory
    ExportResponse response = executeDumpRequest(
            "{\"directory\": \"/tmp/forceDump\"}");

    List<Map<String, Object>> infos = getExports(response);

    assertEquals(2, infos.size());
    assertEquals(0, response.getShardFailures().length);

    // second attempt to dump will fail
    response = executeDumpRequest(
            "{\"directory\": \"/tmp/forceDump\"}");

    infos = getExports(response);
    assertEquals(0, infos.size());
    assertEquals(2, response.getShardFailures().length);

    // if force_overwrite == true a second dump will succeed
    response = executeDumpRequest(
            "{\"directory\": \"/tmp/forceDump\", \"force_overwrite\":true}");

    infos = getExports(response);
    assertEquals(2, infos.size());
    assertEquals(0, response.getShardFailures().length);
}
 
Example 11
Source File: YAMLConfigurationProviderTest.java    From walkmod-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testAddIncludesExcludeInDefault2() throws Exception {
   AddTransformationCommand command = new AddTransformationCommand("imports-cleaner", "mychain", false, null, null,
         null, null, false);
   File file = new File("src/test/resources/yaml/addIncludesInDefault.yml");
   if (file.exists()) {
      file.delete();
   }
   file.createNewFile();
   FileUtils.write(file, "");
   YAMLConfigurationProvider prov = new YAMLConfigurationProvider(file.getPath());
   try {
      prov.createConfig();

      TransformationConfig transfCfg = command.buildTransformationCfg();
      prov.addTransformationConfig("mychain", null, transfCfg, false, null, null);

      command = new AddTransformationCommand("imports-cleaner", null, false, null, null, null, null, false);
      transfCfg = command.buildTransformationCfg();
      prov.addTransformationConfig(null, null, transfCfg, false, null, null);

      prov.addIncludesToChain(null, Arrays.asList("foo"), false, true, false);

      String output = FileUtils.readFileToString(file);
      System.out.println(output);

      Assert.assertTrue(output.contains("foo"));
   } finally {
      if (file.exists()) {
         file.delete();
      }
   }
}
 
Example 12
Source File: LanguageCodesPreferencePage.java    From tmxeditor8 with GNU General Public License v2.0 5 votes vote down vote up
protected void removeLanguage(List<?> languages) {
	try {
		String bundlePath = FileLocator.toFileURL(Activator.getDefault().getBundle().getEntry("")).getPath();
		for (Object object : languages) {
			if (object instanceof Language) {
				Language lang = (Language) object;
				languageModel.removeLanguage(lang);
				LocaleService.getLanguageConfiger().deleteLanguageByCode(lang.getCode());
				String imgPath = lang.getImagePath();
				if (!imgPath.equals("")) {
					File file = new File(bundlePath + imgPath);
					if (file.exists()) {
						file.delete();
					}
				}
			}
		}
	} catch (IOException e) {
		logger.error(Messages.getString("languagecode.LanguageCodesPreferencePage.logger4"), e);
		e.printStackTrace();
	}
	// refresh the viewer
	Tree tree = fFilteredTree.getViewer().getTree();
	try {
		tree.setRedraw(false);
		fFilteredTree.getViewer().refresh();
	} finally {
		tree.setRedraw(true);
	}

}
 
Example 13
Source File: Tools.java    From m2g_android_miner with GNU General Public License v3.0 5 votes vote down vote up
public static void deleteDirectoryContents(final File folder) {
    for (final File f : folder.listFiles()) {

        if (f.isDirectory()) {
            Log.i(LOG_TAG, "Delete Directory: " + f.getName());
            deleteDirectoryContents(f);
        }

        if (f.isFile()) {
            Log.i(LOG_TAG, "Delete File: " + f.getName());
            f.delete();
        }

    }
}
 
Example 14
Source File: FileUtils.java    From sofa-registry with Apache License 2.0 5 votes vote down vote up
public static void deleteDirectory(File directory) throws IOException {
    if (!directory.exists()) {
        return;
    }

    cleanDirectory(directory);
    if (!directory.delete()) {
        String message = "Unable to delete directory " + directory + ".";
        throw new IOException(message);
    }
}
 
Example 15
Source File: GetSize.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    RIFFWriter writer = null;
    RIFFReader reader = null;
    File tempfile = File.createTempFile("test",".riff");
    try
    {
        writer = new RIFFWriter(tempfile, "TEST");
        RIFFWriter chunk = writer.writeChunk("TSCH");
        chunk.writeByte(10);
        writer.close();
        writer = null;
        FileInputStream fis = new FileInputStream(tempfile);
        reader = new RIFFReader(fis);
        RIFFReader readchunk = reader.nextChunk();
        assertEquals(readchunk.getSize(), (long)readchunk.available());
        readchunk.readByte();
        fis.close();
        reader = null;


    }
    finally
    {
        if(writer != null)
            writer.close();
        if(reader != null)
            reader.close();

        if(tempfile.exists())
            if(!tempfile.delete())
                tempfile.deleteOnExit();
    }
}
 
Example 16
Source File: TestContainerLaunch.java    From hadoop with Apache License 2.0 4 votes vote down vote up
@Test (timeout = 20000)
public void testContainerLaunchStdoutAndStderrDiagnostics() throws IOException {

  File shellFile = null;
  try {
    shellFile = Shell.appendScriptExtension(tmpDir, "hello");
    // echo "hello" to stdout and "error" to stderr and exit code with 2;
    String command = Shell.WINDOWS ?
        "@echo \"hello\" & @echo \"error\" 1>&2 & exit /b 2" :
        "echo \"hello\"; echo \"error\" 1>&2; exit 2;";
    PrintWriter writer = new PrintWriter(new FileOutputStream(shellFile));
    FileUtil.setExecutable(shellFile, true);
    writer.println(command);
    writer.close();
    Map<Path, List<String>> resources =
        new HashMap<Path, List<String>>();
    FileOutputStream fos = new FileOutputStream(shellFile, true);

    Map<String, String> env = new HashMap<String, String>();
    List<String> commands = new ArrayList<String>();
    commands.add(command);
    ContainerExecutor exec = new DefaultContainerExecutor();
    exec.writeLaunchEnv(fos, env, resources, commands);
    fos.flush();
    fos.close();

    Shell.ShellCommandExecutor shexc
    = new Shell.ShellCommandExecutor(new String[]{shellFile.getAbsolutePath()}, tmpDir);
    String diagnostics = null;
    try {
      shexc.execute();
      Assert.fail("Should catch exception");
    } catch(ExitCodeException e){
      diagnostics = e.getMessage();
    }
    // test stderr
    Assert.assertTrue(diagnostics.contains("error"));
    // test stdout
    Assert.assertTrue(shexc.getOutput().contains("hello"));
    Assert.assertTrue(shexc.getExitCode() == 2);
  }
  finally {
    // cleanup
    if (shellFile != null
        && shellFile.exists()) {
      shellFile.delete();
    }
  }
}
 
Example 17
Source File: ExcelDownloadView.java    From SI with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private void deleteTempExcelFile(String excelFilePath){
	File excelTempFile = new File(excelFilePath);
	excelTempFile.delete();
}
 
Example 18
Source File: CKEditorController.java    From jpress with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void upload() {

        if (!isMultipartRequest()) {
            renderError(404);
            return;
        }

        UploadFile uploadFile = getFile();
        if (uploadFile == null) {
            renderJson(Ret.create("error", Ret.create("message", "请选择要上传的文件")));
            return;
        }


        File file = uploadFile.getFile();
        if (!getLoginedUser().isStatusOk()){
            file.delete();
            renderJson(Ret.create("error", Ret.create("message", "当前用户未激活,不允许上传任何文件。")));
            return;
        }


        if (AttachmentUtils.isUnSafe(file)){
            file.delete();
            renderJson(Ret.create("error", Ret.create("message", "不支持此类文件上传")));
            return;
        }


        String mineType = uploadFile.getContentType();
        String fileType = mineType.split("/")[0];

        Integer maxImgSize = JPressOptions.getAsInt("attachment_img_maxsize", 2);
        Integer maxOtherSize = JPressOptions.getAsInt("attachment_other_maxsize", 10);
        Integer maxSize = "image".equals(fileType) ? maxImgSize : maxOtherSize;
        int fileSize = Math.round(file.length() / 1024 * 100) / 100;

        if (maxSize != null && maxSize > 0 && fileSize > maxSize * 1024) {
            file.delete();
            renderJson(Ret.create("error", Ret.create("message", "上传文件大小不能超过 " + maxSize + " MB")));
            return;
        }


        String path = AttachmentUtils.moveFile(uploadFile);
        AliyunOssUtils.upload(path, AttachmentUtils.file(path));

        Attachment attachment = new Attachment();
        attachment.setUserId(getLoginedUser().getId());
        attachment.setTitle(uploadFile.getOriginalFileName());
        attachment.setPath(path.replace("\\", "/"));
        attachment.setSuffix(FileUtil.getSuffix(uploadFile.getFileName()));
        attachment.setMimeType(mineType);

        if (attachmentService.save(attachment) != null) {

            /**
             * {"fileName":"1.jpg","uploaded":1,"url":"\/userfiles\/images\/1.jpg"}
             */
            Map map = new HashMap();
            map.put("fileName", attachment.getTitle());
            map.put("uploaded", 1);
            map.put("url", JFinal.me().getContextPath() + attachment.getPath());
            renderJson(map);
        } else {
            renderJson(Ret.create("error", Ret.create("message", "系统错误")));
        }
    }
 
Example 19
Source File: JarOptimizer.java    From awacs with Apache License 2.0 4 votes vote down vote up
static void optimize(final File f) throws IOException {
    if (nodebug && f.getName().contains("debug")) {
        return;
    }

    if (f.isDirectory()) {
        File[] files = f.listFiles();
        for (int i = 0; i < files.length; ++i) {
            optimize(files[i]);
        }
    } else if (f.getName().endsWith(".jar")) {
        File g = new File(f.getParentFile(), f.getName() + ".new");
        ZipFile zf = new ZipFile(f);
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(g));
        Enumeration<? extends ZipEntry> e = zf.entries();
        byte[] buf = new byte[10000];
        while (e.hasMoreElements()) {
            ZipEntry ze = e.nextElement();
            if (ze.isDirectory()) {
                out.putNextEntry(ze);
                continue;
            }
            out.putNextEntry(ze);
            if (ze.getName().endsWith(".class")) {
                ClassReader cr = new ClassReader(zf.getInputStream(ze));
                // cr.accept(new ClassDump(), 0);
                cr.accept(new ClassVerifier(), 0);
            }
            InputStream is = zf.getInputStream(ze);
            int n;
            do {
                n = is.read(buf, 0, buf.length);
                if (n != -1) {
                    out.write(buf, 0, n);
                }
            } while (n != -1);
            out.closeEntry();
        }
        out.close();
        zf.close();
        if (!f.delete()) {
            throw new IOException("Cannot delete file " + f);
        }
        if (!g.renameTo(f)) {
            throw new IOException("Cannot rename file " + g);
        }
    }
}
 
Example 20
Source File: CreateSequenceDictionaryTest.java    From picard with MIT License 4 votes vote down vote up
@Test
public void testAltNames() throws Exception {
    final File altFile = File.createTempFile("CreateSequenceDictionaryTest", ".alt");
    final PrintWriter pw = new PrintWriter(altFile);
    pw.println("chr1\t1");
    pw.println("chr1\t01");
    pw.println("chr1\tk1");
    pw.println("chrMT\tM");
    pw.flush();
    pw.close();
    altFile.deleteOnExit();
    
    final File outputDict = File.createTempFile("CreateSequenceDictionaryTest.", ".dict");
    outputDict.delete();
    outputDict.deleteOnExit();
    final String[] argv = {
            "REFERENCE=" + BASIC_FASTA,
            "AN=" + altFile,
            "OUTPUT=" + outputDict,
            "TRUNCATE_NAMES_AT_WHITESPACE=true"
    };
    Assert.assertEquals(runPicardCommandLine(argv), 0);
    final SAMSequenceDictionary dict = SAMSequenceDictionaryExtractor.extractDictionary(outputDict.toPath());
    Assert.assertNotNull(dict, "dictionary is null");
   
    // check chr1

    final SAMSequenceRecord ssr1 = dict.getSequence("chr1");
    Assert.assertNotNull(ssr1, "chr1 missing in dictionary");
    final String an1 = ssr1.getAttribute("AN");
    Assert.assertNotNull(ssr1, "AN Missing");
    Set<String> anSet = new HashSet<>(Arrays.asList(an1.split("[,]")));

    Assert.assertTrue(anSet.contains("1"));
    Assert.assertTrue(anSet.contains("01"));
    Assert.assertTrue(anSet.contains("k1"));
    Assert.assertFalse(anSet.contains("M"));
    
    // check chr2
    SAMSequenceRecord ssr2 = dict.getSequence("chr2");
    Assert.assertNotNull(ssr2, "chr2 missing in dictionary");
    final String an2 = ssr2.getAttribute("AN");
    Assert.assertNull(an2, "AN Present");
    
    // check chrM
    final SAMSequenceRecord ssrM = dict.getSequence("chrM");
    Assert.assertNull(ssrM, "chrM present in dictionary");
}