Java Code Examples for org.apache.commons.io.FileUtils

The following are top voted examples for showing how to use org.apache.commons.io.FileUtils. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: ExcelParser   File: Properties2Xml.java   View source code 8 votes vote down vote up
/**
 * 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();
    }
}
 
Example 2
Project: jwala   File: ManagedJvmBuilder.java   View source code 7 votes vote down vote up
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);
    }
}
 
Example 3
Project: Cognizant-Intelligent-Test-Scripter   File: HtmlSummaryHandler.java   View source code 6 votes vote down vote up
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());

        }
    }
 
Example 4
Project: atlas   File: ProcessAwoAndroidResources.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 5
Project: instalint   File: PluginCacheTest.java   View source code 6 votes vote down vote up
@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");
}
 
Example 6
Project: convertigo-engine   File: ProjectUtils.java   View source code 6 votes vote down vote up
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);
       	}
   	}
}
 
Example 7
Project: flow-platform   File: SyncServiceTest.java   View source code 6 votes vote down vote up
@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));
}
 
Example 8
Project: csap-core   File: Application.java   View source code 6 votes vote down vote up
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 ) );
	}

}
 
Example 9
Project: Pogamut3   File: ArchetypeRefresh.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 10
Project: osc-core   File: ApplianceUploader.java   View source code 6 votes vote down vote up
@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;
}
 
Example 11
Project: plain-text-archiver   File: Extractor.java   View source code 6 votes vote down vote up
/**
 * 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");
	}
}
 
Example 12
Project: VASSAL-src   File: TempFileManager.java   View source code 6 votes vote down vote up
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;
}
 
Example 13
Project: Android-FileBrowser-FilePicker   File: FileIO.java   View source code 6 votes vote down vote up
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);
    }
}
 
Example 14
Project: BUbiNG   File: ByteArrayDiskQueuesTest.java   View source code 6 votes vote down vote up
@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);
}
 
Example 15
Project: plateyplatey-server   File: SimpleFilesystemConfigurationDAO.java   View source code 6 votes vote down vote up
@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();
}
 
Example 16
Project: obevo   File: PostgreSqlRevengTest.java   View source code 6 votes vote down vote up
@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"));
}
 
Example 17
Project: odoxSync   File: FileProcessorBatchTest.java   View source code 6 votes vote down vote up
@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());

}
 
Example 18
Project: take   File: UpTest.java   View source code 6 votes vote down vote up
@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);
}
 
Example 19
Project: VASSAL-src   File: MapBoard.java   View source code 6 votes vote down vote up
/**
 * @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);
  }
}
 
Example 20
Project: Pogamut3   File: UT2004Match.java   View source code 6 votes vote down vote up
/**
 * 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());
		}
	}
}
 
Example 21
Project: Notebook   File: SyncFragment.java   View source code 6 votes vote down vote up
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);
}
 
Example 22
Project: importador   File: App.java   View source code 6 votes vote down vote up
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();
    }
}
 
Example 23
Project: Sikulix2tesseract   File: LoadLibs.java   View source code 6 votes vote down vote up
/**
 * 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);
        }
    }
}
 
Example 24
Project: AndroTickler   File: ApkToolClass.java   View source code 5 votes vote down vote up
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");;
		}
	}
	
}
 
Example 25
Project: scim2-compliance-test-suite   File: ComplienceUtils.java   View source code 5 votes vote down vote up
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;
}
 
Example 26
Project: Reer   File: TestFile.java   View source code 5 votes vote down vote up
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);
    }
}
 
Example 27
Project: java-lsf   File: LsfTests.java   View source code 5 votes vote down vote up
@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();
}
 
Example 28
Project: Reer   File: PCHUtils.java   View source code 5 votes vote down vote up
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);
    }
}
 
Example 29
Project: FacetExtract   File: TxtToObject.java   View source code 5 votes vote down vote up
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();
	}
}
 
Example 30
Project: emnlp2017-cmapsum-corpus   File: StemSWMatch.java   View source code 5 votes vote down vote up
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();
		}
	}
}
 
Example 31
Project: Pogamut3   File: Tagger.java   View source code 5 votes vote down vote up
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();
	}
}
 
Example 32
Project: monarch   File: LaunchCluster.java   View source code 5 votes vote down vote up
/**
 * 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);
    }
  }

}
 
Example 33
Project: Reer   File: OutputPreparingTaskOutputPacker.java   View source code 5 votes vote down vote up
@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);
}
 
Example 34
Project: butterfly   File: ButterflyCliApp.java   View source code 5 votes vote down vote up
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);
    }
}
 
Example 35
Project: gaffer-doc   File: ExportToOtherGraphExample.java   View source code 5 votes vote down vote up
private void cleanUp() {
    try {
        if (new File("target/ExportToOtherGraphGraphLibrary").exists()) {
            FileUtils.forceDelete(new File("target/ExportToOtherGraphGraphLibrary"));
        }
    } catch (final IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 36
Project: athena   File: YangIoUtils.java   View source code 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 37
Project: osc-core   File: ImportApplianceSoftwareVersionServiceTest.java   View source code 5 votes vote down vote up
@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));
}
 
Example 38
Project: azeroth   File: FastdfsClientTest.java   View source code 5 votes vote down vote up
@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("==========");
}
 
Example 39
Project: athena   File: YangIoUtilsTest.java   View source code 5 votes vote down vote up
/**
 * 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);
}
 
Example 40
Project: verify-hub   File: ConfigAppRule.java   View source code 5 votes vote down vote up
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);
    }
}