Java 类org.apache.commons.io.FileUtils 实例源码

项目:ExcelParser    文件:Properties2Xml.java   
/**
 * Properties 转换 string.xml
 *
 * @param file      properties文件
 * @param xmlCn     中文string.xml
 * @param xmlEn     英文string.xml
 */
public static void properties2Xml(File file, File xmlCn, File xmlEn) {
    try (FileInputStream in = FileUtils.openInputStream(file)){
        List<String> lines = FileUtils.readLines(file);
        // PrintUtils.list(lines);
        // Properties 并不遵循文件原来的顺序,所以采取读行的方式处理
        List<String> xmlLinesCn = new ArrayList<>(lines.size());
        List<String> xmlLinesEn = new ArrayList<>(lines.size());
        addHeader(xmlLinesCn);
        addHeader(xmlLinesEn);
        for(String line : lines){
            xmlLinesCn.add(itemXmlCn(line));
            xmlLinesEn.add(itemXmlEn(line));
        }
        addFooter(xmlLinesCn);
        addFooter(xmlLinesEn);
        FileUtils.deleteQuietly(xmlCn);
        FileUtils.writeLines(xmlCn, "UTF-8", xmlLinesCn);
        FileUtils.writeLines(xmlEn, "UTF-8", xmlLinesEn);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
项目:jwala    文件:ManagedJvmBuilder.java   
protected void createServerXml() {
    final String tomcatConfDir = getTomcatStagingDir().getAbsolutePath() + "/conf";

    if (ifGroupServerXmlExists()) {
        //return, one will be created as a resource
        return;
    }

    String generatedText = generateServerXml();

    LOGGER.debug("Saving template to {}", tomcatConfDir + "/" + SERVER_XML);

    File templateFile = new File(tomcatConfDir + "/" + SERVER_XML);

    try {
        FileUtils.writeStringToFile(templateFile, generatedText, Charset.forName("UTF-8"));
    } catch (IOException e) {
        throw new JvmServiceException(e);
    }
}
项目:convertigo-engine    文件:ProjectUtils.java   
public static void copyIndexFile(String projectName) throws Exception {
    String projectRoot = Engine.PROJECTS_PATH + '/' +  projectName;
    String templateBase = Engine.TEMPLATES_PATH + "/base";
    File indexPage = new File(projectRoot + "/index.html");
    if (!indexPage.exists()) {
        if (new File(projectRoot + "/sna.xsl").exists()) { /** webization javelin */
            if (new File(projectRoot + "/templates/status.xsl").exists()) { /** not DKU / DKU */
                FileUtils.copyFile(new File(templateBase + "/index_javelin.html"), indexPage);
            } else {
                FileUtils.copyFile(new File(templateBase + "/index_javelinDKU.html"), indexPage);
            }
        } else {
            FileFilter fileFilterNoSVN = new FileFilter() {
                public boolean accept(File pathname) {
                    String name = pathname.getName();
                    return !name.equals(".svn") || !name.equals("CVS") || !name.equals("node_modules");
                }
            };
            FileUtils.copyFile(new File(templateBase + "/index.html"), indexPage);
            FileUtils.copyDirectory(new File(templateBase + "/js"), new File(projectRoot + "/js"), fileFilterNoSVN);
            FileUtils.copyDirectory(new File(templateBase + "/css"), new File(projectRoot + "/css"), fileFilterNoSVN);
        }
    }
}
项目:Cognizant-Intelligent-Test-Scripter    文件:HtmlSummaryHandler.java   
private void createStandaloneHtmls() throws IOException {

        createReportIfNotExists(FilePath.getCurrentResultsPath());

        String summaryHtml = FileUtils.readFileToString(new File(FilePath.getSummaryHTMLPath()), Charset.defaultCharset());
        summaryHtml = summaryHtml.replaceAll("../../../../media", "media");
        FileUtils.writeStringToFile(new File(FilePath.getCurrentSummaryHTMLPath()), summaryHtml, Charset.defaultCharset());

        String detailedHtml = FileUtils.readFileToString(new File(FilePath.getDetailedHTMLPath()), Charset.defaultCharset());
        detailedHtml = detailedHtml.replaceAll("../../../../media", "media");
        FileUtils.writeStringToFile(new File(FilePath.getCurrentDetailedHTMLPath()), detailedHtml, Charset.defaultCharset());

        if (perf != null) {
            perf.exportReport();
            String perfHtml = FileUtils.readFileToString(new File(FilePath.getPerfReportHTMLPath()), Charset.defaultCharset());
            perfHtml = perfHtml.replaceAll("../../../../media", "media");
            FileUtils.writeStringToFile(new File(FilePath.getCurrentPerfReportHTMLPath()), perfHtml, Charset.defaultCharset());

        }
    }
项目:atlas    文件:ProcessAwoAndroidResources.java   
/**
 * Read the component's packageId
 *
 * @param packageIdFile
 * @return
 */
private Map<String, String> loadPackageIdProperties(File packageIdFile) throws IOException {
    Map<String, String> values = new HashMap<String, String>();
    if (null != packageIdFile && packageIdFile.exists() && packageIdFile.isFile()) {
        List<String> lines = FileUtils.readLines(packageIdFile);
        for (String line : lines) {
            String[] lineValues = org.apache.commons.lang.StringUtils.split(line, "=");
            if (null != lineValues && lineValues.length >= 2) {
                String key = org.apache.commons.lang.StringUtils.trim(lineValues[0]);
                String value = org.apache.commons.lang.StringUtils.trim(lineValues[1]);
                values.put(key, value);
            }
        }
    }
    return values;
}
项目:instalint    文件:PluginCacheTest.java   
@Test
public void download_and_add_to_cache() throws IOException {
  PluginHashes hashes = mock(PluginHashes.class);
  PluginCache cache = new PluginCache(tempFolder.newFolder().toPath(), hashes);
  when(hashes.of(any(Path.class))).thenReturn("ABCDE");

  PluginCache.Copier downloader = new PluginCache.Copier() {
    public void copy(String filename, Path toFile) throws IOException {
      FileUtils.write(toFile.toFile(), "body");
    }
  };
  File cachedFile = cache.get("sonar-foo-plugin-1.5.jar", "ABCDE", downloader).toFile();
  assertThat(cachedFile).isNotNull().exists().isFile();
  assertThat(cachedFile.getName()).isEqualTo("sonar-foo-plugin-1.5.jar");
  assertThat(cachedFile.getParentFile().getParentFile()).isEqualTo(cache.getCacheDir().toFile());
  assertThat(FileUtils.readFileToString(cachedFile)).isEqualTo("body");
}
项目:flow-platform    文件:SyncServiceTest.java   
@Test
public void should_remove_sync_task_if_create_session_failure() throws Throwable {
    // given: remove stub url
    wireMockRule.resetAll();

    // and copy exist git to workspace
    ClassLoader classLoader = TestBase.class.getClassLoader();
    URL resource = classLoader.getResource("hello.git");
    File path = new File(resource.getFile());
    FileUtils.copyDirectoryToDirectory(path, gitWorkspace.toFile());

    // and: register agent to sync service
    AgentPath agent = agents.get(0);
    syncService.register(agent);

    // when: execute sync task
    syncService.syncTask();

    // then: sync task for agent should be removed
    Assert.assertNull(syncService.getSyncTask(agent));
}
项目:csap-core    文件:Application.java   
public void flushCacheToDisk ( ArrayNode cache, String cacheName ) {
    // TODO Auto-generated method stub

    try {
        File cacheFile = getHostCollectionCacheLocation( cacheName );

        if ( cacheFile.exists() ) {
            logger.error( "Existing file found, should not happen: {}", cacheFile.getCanonicalPath() );
            cacheFile.delete();
        }
        // show during shutdowns - log4j may not be output
        System.out.println( "\n *** Writing cache to disk: {}" + cacheFile.getAbsolutePath() );

        FileUtils.writeStringToFile( cacheFile, jacksonMapper.writeValueAsString( cache ) );
    } catch (Exception e) {
        logger.error( "Failed to store cache {}", CSAP.getCsapFilteredStackTrace( e ) );
    }

}
项目:Pogamut3    文件:ArchetypeRefresh.java   
/**
 * Deletes all .svn dirs from directory recursively.
 * @param dir
 */
protected boolean wipeSVNs(File dir) {
    logInfo("      +--  Wiping .svn dirs from: " + dir.getAbsolutePath());
    if (dir.exists() && dir.isDirectory()) {
        for (File f : dir.listFiles()) {
            if (f.isDirectory() && f.getAbsolutePath().endsWith(".svn")) {
                try {
                    logInfo("        +--  Deleting: " + f.getAbsolutePath());
                    FileUtils.deleteDirectory(f);
                } catch (IOException e) {
                    logSevere(ExceptionToString.process(e));
                    return false;
                }
                continue;
            }
            if (f.isDirectory()) {
                if (!wipeSVNs(f)) return false;
            }
        }
    }
    return true;
}
项目:osc-core    文件:ApplianceUploader.java   
@Override
public OutputStream receiveUpload(String filename, String mimeType) {
    if (filename == null || filename.isEmpty()) {
        return null;
    }
    log.info("Start uploading file: " + filename);
    try {
        if (validateZipFile(filename)) {
            this.uploadPath = getUploadPath(true);
            File uploadDirectory = new File(this.uploadPath);
            if (!uploadDirectory.exists()) {
                FileUtils.forceMkdir(uploadDirectory);
            }
            this.file = new File(this.uploadPath + filename);
            return new FileOutputStream(this.file);
        }

    } catch (Exception e) {
        log.error("Error opening file: " + filename, e);
        ViewUtil.iscNotification(VmidcMessages.getString(VmidcMessages_.UPLOAD_COMMON_ERROR) + e.getMessage(),
                Notification.Type.ERROR_MESSAGE);
    }
    return null;
}
项目:plain-text-archiver    文件:Extractor.java   
/**
 * Extracts the contents of an archive into the output directory.
 * 
 * @param archive The archive to extract.
 * @param outputDirectory The directory to extract it into.
 * @throws IOException
 */
public static void extractArchive(final File archive, final File outputDirectory) throws IOException {
    // Read the archive file.
    String archiveContent = FileUtils.readFileToString(archive, "UTF-8");

    // Create the output directory if it doesn't exist.
    if (!outputDirectory.exists()) {
        outputDirectory.mkdirs();
    }

    // Delete the directory if it already exists for cleanliness, and then recreate it.
    File archiveDirectory = new File(outputDirectory, extractArchiveName(archiveContent));
    if (archiveDirectory.exists()) {
        archiveDirectory.delete();
    }
    archiveDirectory.mkdirs();

    for (FileContent fileContent : extractArchiveFiles(archiveContent)) {
        File file = new File(archiveDirectory.getAbsolutePath() + "/" + fileContent.getFileName());
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        FileUtils.write(file, fileContent.getFileContents(), "UTF-8");
    }
}
项目:VASSAL-src    文件:TempFileManager.java   
private File createSessionRoot() throws IOException {
  // ensure that we have a good temporary root
  if (!tmpRoot.exists() || (!tmpRoot.isDirectory() && !tmpRoot.delete())) {
    FileUtils.forceMkdir(tmpRoot);
  }

  // get the name for our session root
  final File dir = File.createTempFile(DIR_PREFIX, "", tmpRoot);
  // delete it in case a file was created
  dir.delete();

  // create our lock file before creating the directory to prevent
  // a race with another instance of VASSAL
  lock = new File(tmpRoot, dir.getName() + ".lck");
  lock.createNewFile();
  lock.deleteOnExit();

  // now create our session root directory
  FileUtils.forceMkdir(dir);

  return dir;
}
项目:Android-FileBrowser-FilePicker    文件:FileIO.java   
public void createDirectory(final File path) {
    if(path.getParentFile()!=null && path.getParentFile().canWrite()) {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    FileUtils.forceMkdir(path);
                    mUIUpdateHandler.post(mHelper.updateRunner());
                } catch (IOException e) {
                    e.printStackTrace();
                    mUIUpdateHandler.post(mHelper.errorRunner("An error occurred while creating a new folder"));
                }
            }
        });
    } else {
        UIUtils.ShowToast("No Write Permission Granted",mContext);
    }
}
项目:BUbiNG    文件:ByteArrayDiskQueuesTest.java   
@Test
public void testReadWriteVByte() throws IOException {
    final File dir = File.createTempFile(ByteArrayDiskQueuesTest.class.getName() + "-", "-temp");
    dir.delete();
    dir.mkdir();
    final ByteArrayDiskQueues queues = new ByteArrayDiskQueues(dir, LOG2_LOG_FILE_SIZE);

    final XoRoShiRo128PlusRandom random = new XoRoShiRo128PlusRandom(1);
    queues.pointer(0);
    for(int i = 0; i < 10000000; i++) queues.encodeInt(random.nextInt(Integer.MAX_VALUE));
    queues.pointer(0);
    random.setSeed(1);
    for(int i = 0; i < 10000000; i++) assertEquals(random.nextInt(Integer.MAX_VALUE), queues.decodeInt());

    queues.close();
    FileUtils.deleteDirectory(dir);
}
项目:plateyplatey-server    文件:SimpleFilesystemConfigurationDAO.java   
@Override
public Optional<Configuration> getConfigurationById(ConfigurationId id) {

    final File configurationFile = new File(this.configurationsDir, id.toString());

    if (configurationFile.exists()) {
        try {
            final String configurationText = FileUtils.readFileToString(configurationFile, Charset.defaultCharset());
            final Configuration configuration = JSON_MAPPER.readValue(configurationText, Configuration.class);

            return Optional.of(configuration);
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    } else return Optional.empty();
}
项目:obevo    文件:PostgreSqlRevengTest.java   
@Test
@Override
public void testReverseEngineeringFromFile() throws Exception {
    AquaRevengArgs args = new AquaRevengArgs();
    args.setDbSchema("myschema01");
    args.setGenerateBaseline(false);
    args.setDbHost("myhost.me.com");
    args.setDbPort(1234);
    args.setDbServer("myserver");
    args.setUsername("myuser");
    args.setPassword("mypass");

    File outputDir = new File("./target/outputReveng");
    FileUtils.deleteDirectory(outputDir);
    args.setOutputPath(outputDir);

    args.setInputPath(new File("./src/test/resources/reveng/pgdump/input/input.sql"));

    new PostgreSqlDbPlatform().getDdlReveng().reveng(args);

    DirectoryAssert.assertDirectoriesEqual(new File("./src/test/resources/reveng/pgdump/expected"), new File(outputDir, "final"));
}
项目:odoxSync    文件:FileProcessorBatchTest.java   
@Test
public void batch_should_skip_on_second_scan() throws IOException {
    long fileSize = ((Contants.REGION_SIZE * SlowFileProcessor.BATCH_SIZE) * 2) + 1;
    String workingDirectory = "/home/gaganis/IdeaProjects/DirectorySynchronizer/testdata/source";
    String fileName = "ubuntu-16.04.1-desktop-amd64.iso";
    File file = new File(fileName);
    updateAbsolutePath(file, workingDirectory, fileName);

    FileProcessor fileProcessor = getFileProcessor(fileSize, workingDirectory, file);
    BatchArea batchArea = fileProcessor.nextBatchArea();
    assertThat(batchArea.isSkip).isFalse();

    fileProcessor.doBeforeBatchByteRead();
    fileProcessor.process(
            new byte[(int) (Contants.REGION_SIZE * SlowFileProcessor.BATCH_SIZE)],
            batchArea);
    fileProcessor = getFileProcessor(fileSize, workingDirectory, file);
    batchArea = fileProcessor.nextBatchArea();
    assertThat(batchArea.isSkip).isTrue();
    FileUtils.touch(file.getAbsolutePath().toFile());

}
项目:take    文件:UpTest.java   
@Test
public void test01() throws Exception {
    List<String> lines = FileUtils.readLines(new File("E:\\stock\\up.txt"));
    List<Stock> stocks = new ArrayList<>();
    for (String line : lines) {
        System.out.println(line);
        if (line.startsWith("股票")) {
            continue;
        }
        String[] split = line.split("\\t");
        String name = split[0];
        String up = split[3];
        String hangye = split[4].split("\\-")[0];
        stocks.add(new Stock(name, up, hangye));
    }

    FileUtils.writeLines(new File("e:/stock/up2.txt"), stocks);
    System.out.println(stocks);
}
项目:VASSAL-src    文件:MapBoard.java   
/**
 * @throws IOException
 */
protected Rectangle writeImageToArchive() throws IOException {
  // write image to archive
  final BufferedImage image = getLayerImage();
  if (image == null) {
    return null;
  }

  final Rectangle r = getCropRectangle(image);
  if (r.width == 0 || r.height == 0) {
    return null;
  }

  final File f = File.createTempFile("map", ".png", Info.getTempDir());
  try {
    ImageIO.write(image.getSubimage(r.x, r.y, r.width, r.height), "png", f);
    imageName = getUniqueImageFileName(getName(), ".png");
    GameModule.getGameModule()
              .getArchiveWriter()
              .addImage(f.getPath(), imageName);
    return r;
  }
  finally {
    FileUtils.forceDelete(f);
  }
}
项目:Pogamut3    文件:UT2004Match.java   
/**
 * Optional (usually) STEP 11 ... moves replay file to desired directory.  
 * @param ucc
 * @param fileName
 */
protected void copyReplay(UCCWrapper ucc, String fileName, File outputDirectory) {
    if (log != null && log.isLoggable(Level.FINE)) {
        log.fine(config.getMatchId().getToken() + ": Copying replay file into " + outputDirectory.getAbsolutePath());
    }
    File replayFile = new File(ucc.getConfiguration().getUnrealHome() + File.separator + "Demos" + File.separator + fileName + ".demo4");
    File destination = new File(outputDirectory.getAbsoluteFile() + File.separator + "match-" + config.getMatchId().getToken() + "-replay.demo4");
    FilePath.makeDirsToFile(destination);
    boolean ex = false;
    try {
        FileUtils.copyFile(replayFile, destination);
    } catch (IOException e) {
        ex = true;
        if (log != null) {
            log.warning(config.getMatchId().getToken() + ": Failed to copy replay file from: " + replayFile.getAbsolutePath() + " into " + destination.getAbsolutePath() + ": " + e.getMessage());
        }
    }       
    if (!ex) {
        if (log != null && log.isLoggable(Level.INFO)) {
            log.info(config.getMatchId().getToken() + ": Replay copied into " + destination.getAbsolutePath());
        }
    }
}
项目:Notebook    文件:SyncFragment.java   
private void sync() {
    File tempFile = new File(Constants.CONFIG_TEMP_DB);
    if(!tempFile.exists()){
        DialogHelper.alert("����", "ͬ���ļ������ڣ��������غ���ͬ����");
        return;
    }
    progressbar.setVisible(true);
    progressbar.setProgress(-1f);
    progressbar.setProgress(0.5f);
    progressbar.setProgress(-1f);
    iv_down.setDisable(true);
    iv_sync.setDisable(true);

    String projectDir = System.getProperty("user.dir");
    File destFile = new File(projectDir,"notebook.db");

    try {
        byte[] data = FileUtils.readFileToByteArray(tempFile);
        FileUtils.writeByteArrayToFile(destFile, data);
    } catch (IOException e) {
        e.printStackTrace();
        DialogHelper.alert("Error", e.toString());
    }
    progressbar.setProgress(1f);
    iv_down.setDisable(false);
    iv_sync.setDisable(false);
    DialogHelper.alert("Success", "ͬ���ɹ���-> \r\n" + tempFile.getAbsolutePath() + " �ѱ��ƶ��� " + projectDir);
}
项目:importador    文件:App.java   
private void processFile(final String host, final String sid, final String user, final String password,
                         final String filePath) throws IOException {

    final File file = new File(filePath);
    final List<String> lines = FileUtils.readLines(file, "UTF-8");

    final int numThreads = 50;
    final int sublinhas = lines.size() / numThreads;

    System.out.println("Started at " + new Date().toString());

    for (int i = 0; i < numThreads; i++) {
        new Insersor(host, sid, user, password, lines.subList(i * sublinhas, ((i + 1) * sublinhas))).start();
    }

    int resto = lines.size() % numThreads;
    if (resto != 0) {
        new Insersor(host, sid, user, password, lines.subList(lines.size() - resto, lines.size())).start();
    }
}
项目:Sikulix2tesseract    文件:LoadLibs.java   
/**
 * Copies resources to target folder.
 *
 * @param resourceUrl
 * @param targetPath
 * @return
 */
static void copyResources(URL resourceUrl, File targetPath) throws IOException {
    if (resourceUrl == null) {
        return;
    }

    URLConnection urlConnection = resourceUrl.openConnection();

    /**
     * Copy resources either from inside jar or from project folder.
     */
    if (urlConnection instanceof JarURLConnection) {
        copyJarResourceToPath((JarURLConnection) urlConnection, targetPath);
    } else {
        File file = new File(resourceUrl.getPath());
        if (file.isDirectory()) {
            FileUtils.copyDirectory(file, targetPath);
        } else {
            FileUtils.copyFile(file, targetPath);
        }
    }
}
项目:AndroTickler    文件:ApkToolClass.java   
private void deleteExistingDecodedDir(){
    File decodedDir = new File (TicklerVars.extractedDir);
    if (decodedDir.exists()){
        try{
            FileUtils.deleteDirectory(decodedDir);
            System.out.println("Existing SMALI directory will be deleted....");
        }
        catch(IOException e){
            System.out.println("Cannot delete old extracted directory "+decodedDir.getAbsolutePath()+"\nPlease delete it manually and repeat");;
        }
    }

}
项目:scim2-compliance-test-suite    文件:ComplienceUtils.java   
public static User getUser() {
    try {
        String fullUser = FileUtils.readFileToString(new File("src/main/resources/user_full.json"));
        return new User(fullUser, User.ENCODING_JSON);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
项目:Reer    文件:TestFile.java   
public String getText() {
    assertIsFile();
    try {
        return FileUtils.readFileToString(this);
    } catch (IOException e) {
        throw new RuntimeException(String.format("Could not read from test file '%s'", this), e);
    }
}
项目:java-lsf    文件:LsfTests.java   
@Before
public void setupDirs() throws IOException {

    rootPath = Paths.get(".").toAbsolutePath().normalize();
    scriptDirPath = rootPath.resolve("src/test/bash");
    inputDirPath = rootPath.resolve("src/test/resources");
    outputDirPath = rootPath.resolve("target/test");

    // Recreate the output directory
    FileUtils.deleteDirectory(outputDirPath.toFile());
    outputDirPath.toFile().mkdirs();
}
项目:Reer    文件:PCHUtils.java   
public static File generatePCHObjectDirectory(File tempDir, File prefixHeaderFile, File preCompiledHeaderObjectFile) {
    File generatedDir = new File(tempDir, "preCompiledHeaders");
    generatedDir.mkdirs();
    File generatedHeader = new File(generatedDir, prefixHeaderFile.getName());
    File generatedPCH = new File(generatedDir, preCompiledHeaderObjectFile.getName());
    try {
        FileUtils.copyFile(prefixHeaderFile, generatedHeader);
        FileUtils.copyFile(preCompiledHeaderObjectFile, generatedPCH);
        return generatedDir;
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
项目:FacetExtract    文件:TxtToObject.java   
public static void writeObjToTxt(Topic topic, String txtPath) {
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    try {
        FileUtils.write(new File(txtPath), gson.toJson(topic), "utf-8");
    } catch (IOException e) {
        e.printStackTrace();
    }
}
项目:emnlp2017-cmapsum-corpus    文件:StemSWMatch.java   
public StemSWMatch(URL stopwordFile) {
    this.stemmer = new SnowballStemmer(ALGORITHM.ENGLISH);
    this.stopwords = new HashSet<String>();
    if (stopwordFile != null) {
        try {
            for (String word : FileUtils.readLines(new File(stopwordFile.getPath()))) {
                this.stopwords.add(word);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
项目:Pogamut3    文件:Tagger.java   
private void unpack(InputStream stream) throws IOException {
    log.info("Exctracting Jacobe...");
    FileUtils.copyInputStreamToFile(stream, new File("temp_jacobe.zip"));
    try {
        File dir = new File("temp_jacobe_unpacked");
        if (!dir.mkdir()) {
            log.warning("Deleting " + dir.getAbsolutePath() + " ...");
            FileUtils.deleteQuietly(dir);
            if (!dir.mkdir()) {
                throw new IOException("Failed to create dir 'temp_jacobe_unpacked'!");
            }
        }

        ZipFile zipFile = new ZipFile(new File("temp_jacobe.zip"));
        try {
            Enumeration entries = zipFile.entries();

            while (entries.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) entries.nextElement();

                if (entry.isDirectory()) {
                    throw new RuntimeException("Jacobe's zip file should not contain directories!");

                }
                log.info("Extracting file: " + entry.getName());
                FileUtils.copyInputStreamToFile(zipFile.getInputStream(entry), new File("temp_jacobe_unpacked/" + entry.getName()));
            }
        } finally {
            zipFile.close();
        }
    } finally {
        new File("temp_jacobe.zip").delete();
    }
}
项目:monarch    文件:LaunchCluster.java   
/**
 * This clean cluster's parent dir. Important for test cases it will wipe out logs etc
 *
 * @param dir - Cluster dir path
 * @throws ClusterException
 */
public static void cleanupDir(String dir) throws ClusterException {
  File workDir = new File(dir);
  if (workDir.exists()) {
    try {
      FileUtils.forceDelete(workDir);
    } catch (IOException e) {
      throw new ClusterException(e.getMessage(), e);
    }
  }

}
项目:Reer    文件:OutputPreparingTaskOutputPacker.java   
@Override
public void unpack(TaskOutputsInternal taskOutputs, InputStream input, TaskOutputOriginReader readOrigin) {
    for (TaskOutputFilePropertySpec propertySpec : taskOutputs.getFileProperties()) {
        CacheableTaskOutputFilePropertySpec property = (CacheableTaskOutputFilePropertySpec) propertySpec;
        File output = property.getOutputFile();
        if (output == null) {
            continue;
        }
        try {
            switch (property.getOutputType()) {
                case DIRECTORY:
                    makeDirectory(output);
                    FileUtils.cleanDirectory(output);
                    break;
                case FILE:
                    if (!makeDirectory(output.getParentFile())) {
                        if (output.exists()) {
                            FileUtils.forceDelete(output);
                        }
                    }
                    break;
                default:
                    throw new AssertionError();
            }
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }
    delegate.unpack(taskOutputs, input, readOrigin);
}
项目:butterfly    文件:ButterflyCliApp.java   
private static void writeResultFile(ButterflyCliRun run) {
    GsonBuilder gsonBuilder = new GsonBuilder().setPrettyPrinting();
    Gson gson = gsonBuilder.create();
    String runJsonString = gson.toJson(run);
    File resultFile = (File) optionSet.valueOf(CLI_OPTION_RESULT_FILE);
    try {
        FileUtils.writeStringToFile(resultFile, runJsonString, Charset.defaultCharset());
    } catch (IOException e) {
        logger.error("Error when writing CLI result file", e);
    }
}
项目:gaffer-doc    文件:ExportToOtherGraphExample.java   
private void cleanUp() {
    try {
        if (new File("target/ExportToOtherGraphGraphLibrary").exists()) {
            FileUtils.forceDelete(new File("target/ExportToOtherGraphGraphLibrary"));
        }
    } catch (final IOException e) {
        throw new RuntimeException(e);
    }
}
项目:athena    文件:YangIoUtils.java   
/**
 * Searches and deletes generated temporary directories.
 *
 * @param root root directory
 * @throws IOException when fails to do IO operations.
 */
public static void searchAndDeleteTempDir(String root)
        throws IOException {
    List<File> store = new LinkedList<>();
    Stack<String> stack = new Stack<>();
    stack.push(root);

    while (!stack.empty()) {
        root = stack.pop();
        File file = new File(root);
        File[] filelist = file.listFiles();
        if (filelist == null || filelist.length == 0) {
            continue;
        }
        for (File current : filelist) {
            if (current.isDirectory()) {
                stack.push(current.toString());
                if (current.getName().endsWith("-Temp")) {
                    store.add(current);
                }
            }
        }
    }

    for (File dir : store) {
        FileUtils.deleteDirectory(dir);
    }
}
项目:osc-core    文件:ImportApplianceSoftwareVersionServiceTest.java   
@Test
public void testDispatch_ImportApplianceMissingPayloadFile_ExpectsErrorResponse() throws Exception {
    // Arrange. Make sure input is missing a file
    PowerMockito.when(FileUtil.getFileListFromDirectory(anyString()))
    .thenReturn(new File[] { this.mockMetaDataFile });
    Mockito.when(FileUtils.readFileToString(this.mockMetaDataFile, Charset.defaultCharset()))
    .thenReturn(new Gson().toJson(this.imageMetaData));

    this.exception.expect(VmidcBrokerValidationException.class);
    this.exception.expectMessage("missing in archive");

    // Act.
    this.service.dispatch(new ImportFileRequest(TEST_TMP_FOLDER));
}
项目:azeroth    文件:FastdfsClientTest.java   
@Test
public void testUpload2() throws Exception {

    byte[] byteArray = FileUtils.readFileToByteArray(new File("/Users/ayg/Desktop/logo.gif"));
    CompletableFuture<FileId> path = client.upload("123.gif", byteArray);
    FileId fileId = path.get();
    System.out.println(fileId);
    CompletableFuture<FileMetadata> metadataGet = client.metadataGet(fileId);
    System.out.println(metadataGet.get(10, TimeUnit.SECONDS));
    System.out.println("==========");
}
项目:athena    文件:YangIoUtilsTest.java   
/**
 * This test case tests whether the directories are getting created.
 */
@Test
public void createDirectoryTest() throws IOException {

    File dirPath = createDirectories(CREATE_PATH);
    assertThat(dirPath.isDirectory(), is(true));
    FileUtils.deleteDirectory(dirPath);
}
项目:verify-hub    文件:ConfigAppRule.java   
private void writeFile(File folder, int index, Object content) {
    try {
        FileUtils.write(new File(folder.getAbsolutePath(), folder.getName() + Integer.toString(index) + ".yml"), mapper.writeValueAsString(content));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}