當前位置: 首頁>>代碼示例>>Java>>正文


Java FileUtils類代碼示例

本文整理匯總了Java中org.apache.commons.io.FileUtils的典型用法代碼示例。如果您正苦於以下問題:Java FileUtils類的具體用法?Java FileUtils怎麽用?Java FileUtils使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


FileUtils類屬於org.apache.commons.io包,在下文中一共展示了FileUtils類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: createServerXml

import org.apache.commons.io.FileUtils; //導入依賴的package包/類
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);
    }
}
 
開發者ID:cerner,項目名稱:jwala,代碼行數:21,代碼來源:ManagedJvmBuilder.java

示例2: properties2Xml

import org.apache.commons.io.FileUtils; //導入依賴的package包/類
/**
 * 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();
    }
}
 
開發者ID:linchaolong,項目名稱:ExcelParser,代碼行數:30,代碼來源:Properties2Xml.java

示例3: copyIndexFile

import org.apache.commons.io.FileUtils; //導入依賴的package包/類
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);
       	}
   	}
}
 
開發者ID:convertigo,項目名稱:convertigo-engine,代碼行數:25,代碼來源:ProjectUtils.java

示例4: createStandaloneHtmls

import org.apache.commons.io.FileUtils; //導入依賴的package包/類
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());

        }
    }
 
開發者ID:CognizantQAHub,項目名稱:Cognizant-Intelligent-Test-Scripter,代碼行數:21,代碼來源:HtmlSummaryHandler.java

示例5: loadPackageIdProperties

import org.apache.commons.io.FileUtils; //導入依賴的package包/類
/**
 * 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;
}
 
開發者ID:alibaba,項目名稱:atlas,代碼行數:22,代碼來源:ProcessAwoAndroidResources.java

示例6: download_and_add_to_cache

import org.apache.commons.io.FileUtils; //導入依賴的package包/類
@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");
}
 
開發者ID:instalint-org,項目名稱:instalint,代碼行數:18,代碼來源:PluginCacheTest.java

示例7: unpack

import org.apache.commons.io.FileUtils; //導入依賴的package包/類
@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);
}
 
開發者ID:lxxlxx888,項目名稱:Reer,代碼行數:31,代碼來源:OutputPreparingTaskOutputPacker.java

示例8: writeResultFile

import org.apache.commons.io.FileUtils; //導入依賴的package包/類
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);
    }
}
 
開發者ID:paypal,項目名稱:butterfly,代碼行數:12,代碼來源:ButterflyCliApp.java

示例9: should_remove_sync_task_if_create_session_failure

import org.apache.commons.io.FileUtils; //導入依賴的package包/類
@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));
}
 
開發者ID:FlowCI,項目名稱:flow-platform,代碼行數:22,代碼來源:SyncServiceTest.java

示例10: flushCacheToDisk

import org.apache.commons.io.FileUtils; //導入依賴的package包/類
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 ) );
	}

}
 
開發者ID:csap-platform,項目名稱:csap-core,代碼行數:20,代碼來源:Application.java

示例11: wipeSVNs

import org.apache.commons.io.FileUtils; //導入依賴的package包/類
/**
 * 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;
}
 
開發者ID:kefik,項目名稱:Pogamut3,代碼行數:26,代碼來源:ArchetypeRefresh.java

示例12: receiveUpload

import org.apache.commons.io.FileUtils; //導入依賴的package包/類
@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;
}
 
開發者ID:opensecuritycontroller,項目名稱:osc-core,代碼行數:25,代碼來源:ApplianceUploader.java

示例13: extractArchive

import org.apache.commons.io.FileUtils; //導入依賴的package包/類
/**
 * 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");
	}
}
 
開發者ID:Aelexe,項目名稱:plain-text-archiver,代碼行數:32,代碼來源:Extractor.java

示例14: createSessionRoot

import org.apache.commons.io.FileUtils; //導入依賴的package包/類
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;
}
 
開發者ID:ajmath,項目名稱:VASSAL-src,代碼行數:23,代碼來源:TempFileManager.java

示例15: process

import org.apache.commons.io.FileUtils; //導入依賴的package包/類
@Override
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
public FResult<JSONObject> process(UploadRequest request) throws Exception {
  Long commonFileId = null;
  try {
    File temporaryFile = new File(request.getTemporaryFilePath());
    if (temporaryFile == null || !temporaryFile.isFile() || !temporaryFile.exists()) {
      return FResult.newFailure(HttpResponseCode.SERVER_IO_READ, "上傳失敗");
    }
    String currentFileMd5 = request.getTemporaryFileMd5();
    String fileId = uploadFileReturnFileId(request.getTemporaryFilePath(), request.getSuffix());
    if (StringUtils.isBlank(fileId)) {
      return FResult.newFailure(HttpResponseCode.SERVER_IO_WRITE, "上傳文件到FastDFS失敗,請檢查FastDFS日誌");
    }
    long nowTimestamp = System.currentTimeMillis();
    // 要保存的對象
    UploadFile commonFile = new UploadFile();
    commonFile.setFilemd5(currentFileMd5);
    // 保存主文件後,返回住表ID
    log.debug("你可以控製是否要持久化這個文件");
    commonFileId = commonFileService.addUploadFile(nowTimestamp, commonFile, temporaryFile, request, fileId);
    if (commonFileId == null || commonFileId == 0) {
      log.error("insert common_file failed,record:" + JSON.toJSONString(commonFile));
      FileUtils.forceDelete(temporaryFile);
      return FResult.newFailure(HttpResponseCode.SERVER_DB_ERROR, "保存上傳記錄失敗");
    }
    return buildResult(request.getOriginalFilename(), request.getTemporaryFileSize(), request.getTemporaryFileMd5(), commonFile.getUrl(),
        commonFile.getId());
  } catch (Exception uploadException) {
    log.error("普通文件上傳過程中發生錯誤", uploadException);
    return FResult.newFailure(HttpResponseCode.SERVER_ERROR, "文件上傳過程中發生錯誤");
  }
}
 
開發者ID:devpage,項目名稱:fastdfs-quickstart,代碼行數:34,代碼來源:SimpleJsonFileUploadProcessor.java


注:本文中的org.apache.commons.io.FileUtils類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。