当前位置: 首页>>代码示例>>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;未经允许,请勿转载。