Java Code Examples for org.apache.commons.io.FileUtils.readFileToString()

The following are Jave code examples for showing how to use readFileToString() of the org.apache.commons.io.FileUtils class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: iaac4j.aliyun   File: FileLoader.java   View Source Code Vote up 6 votes
/**
 * 从文件系统读取一个资源,使用当前ClassLoader读取相对路径
 * @return 资源的字符串
 * @throws Exception 资源不存在
 */
@Override
public String load() throws Exception {
    String result = null;
    try {
        String path = this.url;
        if (this.fileName != null) {
            path = path + "/" + this.fileName;
        }
        URL pathUrl = FileLoader.class.getClassLoader().getResource(path);
        result = FileUtils.readFileToString(new File(pathUrl.getPath()), "utf-8");
    } catch (Exception e) {
        throw e;
    }
    return result;
}
 
Example 2
Project: Open_Source_ECOA_Toolset_AS5   File: InitAssemblyEditor.java   View Source Code Vote up 6 votes
@Override
protected void initializeGraphicalViewer() {
	super.initializeGraphicalViewer();
	getGraphicalViewer().setRootEditPart(new ScalableFreeformRootEditPart());
	FileEditorInput inp = (FileEditorInput) getEditorInput();
	setPartName(inp.getFile().getName());
	try {
		String path = inp.getFile().getLocation().toOSString();
		String text = FileUtils.readFileToString(new File(path));
		CompositeNode node = parse(text);
		root = new CompositeEditPart(node, inp.getFile().getProject().getFullPath().toOSString());
		getGraphicalViewer().setContents(root);
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example 3
Project: cas-5.1.0   File: ReturnMappedAttributeReleasePolicy.java   View Source Code Vote up 6 votes
private static void processFileBasedGroovyAttributes(final Map<String, Object> resolvedAttributes,
                                                     final Map<String, Object> attributesToRelease,
                                                     final Matcher matcherFile, final Object[] entry) {
    try {
        LOGGER.debug("Found groovy script to execute for attribute mapping [{}]", entry[0]);
        final String script = FileUtils.readFileToString(new File(matcherFile.group(1)), StandardCharsets.UTF_8);
        final Object result = getGroovyAttributeValue(script, resolvedAttributes);
        if (result != null) {
            LOGGER.debug("Mapped attribute [{}] to [{}] from script", entry[0], result);
            attributesToRelease.put(entry[0].toString(), result);
        } else {
            LOGGER.warn("Groovy-scripted attribute returned no value for [{}]", entry[0]);
        }
    } catch (final IOException e) {
        LOGGER.error(e.getMessage(), e);
    }
}
 
Example 4
Project: Habanero   File: JSONReportMerger.java   View Source Code Vote up 6 votes
/**
 * Give unique names to embedded images to ensure they aren't lost during merge
 * Update report file to reflect new image names
 *
 * @param reportFile
 */
public void renameEmbededImages(File reportFile) throws Throwable {
    File reportDirectory = reportFile.getParentFile();
    Collection<File> embeddedImages = FileUtils.listFiles(reportDirectory, new String[]{reportImageExtension}, true);

    String fileAsString = FileUtils.readFileToString(reportFile);

    for (File image : embeddedImages) {
        String curImageName = image.getName();
        String uniqueImageName = reportDirectory.getName() + "-" + UUID.randomUUID().toString() + "." + reportImageExtension;

        image.renameTo(new File(reportDirectory, uniqueImageName));
        fileAsString = fileAsString.replace(curImageName, uniqueImageName);
    }

    FileUtils.writeStringToFile(reportFile, fileAsString);
}
 
Example 5
Project: formatter   File: FormatUtil.java   View Source Code Vote up 6 votes
/**
* 
* @Title: openFile 
* @Description: open file to get file content 
* @param @param parent
* @param @param fc
* @param @return 
* @return String
* @throws
 */
public static String openFile(Component parent, JFileChooser fc)
{
    String content = StringUtils.EMPTY;
    int retVal = fc.showOpenDialog(parent);
    if (JFileChooser.APPROVE_OPTION != retVal)
    {
        return content;
    }

    try
    {
        File sf = fc.getSelectedFile();
        content = FileUtils.readFileToString(sf, Charsets.UTF_8.getCname());
    }
    catch(IOException e)
    {
        FormatView.getView().getStat().setText("Failed to read file: " + e.getMessage());
    }

    return content;
}
 
Example 6
Project: hadoop   File: TestWinUtils.java   View Source Code Vote up 6 votes
@SuppressWarnings("deprecation")
@Test(timeout=10000)
public void testTaskCreate() throws IOException {
  File batch = new File(TEST_DIR, "testTaskCreate.cmd");
  File proof = new File(TEST_DIR, "testTaskCreate.out");
  FileWriter fw = new FileWriter(batch);
  String testNumber = String.format("%f", Math.random());
  fw.write(String.format("echo %s > \"%s\"", testNumber, proof.getAbsolutePath()));
  fw.close();
  
  assertFalse(proof.exists());
  
  Shell.execCommand(Shell.WINUTILS, "task", "create", "testTaskCreate" + testNumber, 
      batch.getAbsolutePath());
  
  assertTrue(proof.exists());
  
  String outNumber = FileUtils.readFileToString(proof);
  
  assertThat(outNumber, containsString(testNumber));
}
 
Example 7
Project: WeiMusicCommunity-server   File: CommityManageService.java   View Source Code Vote up 5 votes
public CommityInfo getCommityInfoByCName(String CName) throws IOException {

        CommityInfo re = commityManageDao.getCommmityInfoByCName(CName);
        File imgPath = new File(StaticVar.getToFilePath() + re.getCHeadImg());
        String imgEncode = FileUtils.readFileToString(imgPath, StaticVar.getDecodeFileSet());
        re.setCImgObj(imgEncode);
        return re;
    }
 
Example 8
Project: stvs   File: ImporterFacadeTest.java   View Source Code Vote up 5 votes
@Test
public void importSessionFile() throws Exception {
  StvsRootModel importedSession = ImporterFacade.importSession(new File(XmlSessionImporter.class
          .getResource("session_valid_1.xml").toURI().getPath()),
      ImporterFacade.ImportFormat.XML, new GlobalConfig(), new History());
  String code = FileUtils.readFileToString(new File(StvsApplication.class.getResource
      ("testSets/valid_1/code_valid_1.st").toURI()), "utf-8");
  Assert.assertEquals(TestUtils.removeWhitespace(code), TestUtils.removeWhitespace(importedSession.getScenario()
      .getCode().getSourcecode()));
}
 
Example 9
Project: TOSCAna   File: CloudFoundryPluginTest.java   View Source Code Vote up 5 votes
@Test
public void getDeployScript() throws Exception {
    File targetFile = new File(targetDir + "/output/scripts/", FILEPRAEFIX_DEPLOY + appName +
        FILESUFFIX_DEPLOY);
    String deployScript = FileUtils.readFileToString(targetFile);
    String expectedOutput = String.format("#!/bin/sh\nsource util/*\ncheck \"cf\"\n%smy_db\n%s%s%s%s\n",
        CLI_CREATE_SERVICE_DEFAULT, CLI_PUSH, appName, CLI_PATH_TO_MANIFEST, MANIFEST_NAME);

    assertEquals(expectedOutput, deployScript);
}
 
Example 10
Project: SensorThingsProcessor   File: ProcessorWrapper.java   View Source Code Vote up 5 votes
public void doProcess(Options options) {
    this.noAct = options.getNoAct().isSet();
    this.online = options.getOnline().isSet();
    String fileName = options.getFileName().getValue();
    File configFile = new File(fileName);
    try {
        String config = FileUtils.readFileToString(configFile, "UTF-8");
        doProcess(config, noAct, online);
    } catch (IOException ex) {
        LOGGER.error("Failed to read config file.", ex);
    }
}
 
Example 11
Project: cas-5.1.0   File: SamlMetadataController.java   View Source Code Vote up 5 votes
/**
 * Displays the identity provider metadata.
 * Checks to make sure metadata exists, and if not, generates it first.
 *
 * @param response servlet response
 * @throws IOException the iO exception
 */
@GetMapping(path = SamlIdPConstants.ENDPOINT_IDP_METADATA)
public void generateMetadataForIdp(final HttpServletResponse response) throws IOException {
    final File metadataFile = this.metadataAndCertificatesGenerationService.performGenerationSteps();
    final String contents = FileUtils.readFileToString(metadataFile, StandardCharsets.UTF_8);
    response.setContentType(CONTENT_TYPE);
    response.setStatus(HttpServletResponse.SC_OK);
    try (PrintWriter writer = response.getWriter()) {
        LOGGER.debug("Producing metadata for the response");
        writer.write(contents);
        writer.flush();
    }
}
 
Example 12
Project: neo-java   File: ConfigurationUtil.java   View Source Code Vote up 5 votes
/**
 * return the configuration JSON object.
 *
 * @return the configuration JSON object.
 * @throws IOException
 *             if an error occurs.
 */
public static JSONObject getConfiguration() {
	try {
		final JSONObject controllerNodeConfig = new JSONObject(
				FileUtils.readFileToString(CONFIG_FILE, Charset.defaultCharset()));
		final int nonce = ThreadLocalRandom.current().nextInt(Integer.MAX_VALUE);
		controllerNodeConfig.put(ConfigurationUtil.NONCE, nonce);
		return controllerNodeConfig;
	} catch (final IOException e) {
		throw new RuntimeException(e);
	}
}
 
Example 13
Project: rate-limiting   File: ConfigurationLoader.java   View Source Code Vote up 5 votes
private RateLimitingSettings loadConfigFromFile(String filename, String filterKey)
		throws JsonProcessingException, IOException {
	logger.info("Loading configuration from file " + filename);
	File file = new File(filename);
	if (!file.exists())
		throw new IllegalArgumentException("File " + filename + " doesn't exist!");

	String raw = FileUtils.readFileToString(file);
	return fromString(raw, filterKey);
}
 
Example 14
Project: goobi-viewer-indexer   File: SerializingSolrWriteStrategy.java   View Source Code Vote up 5 votes
/**
 * 
 * @param order
 * @param rootDoc
 * @param aggregateRecords
 * @throws FatalIndexerException
 */
private void writePageDoc(int order, SolrInputDocument rootDoc, boolean aggregateRecords) throws FatalIndexerException {
    String iddoc = pageDocOrderIddocMap.get(order);
    SolrInputDocument doc = load(iddoc);
    if (doc != null) {
        // doc.setField(SolrConstants.ORDER, newOrder); // make sure order starts at 1 in the end
        {
            Path xmlFile = Paths.get(tempFolder.toAbsolutePath().toString(), new StringBuilder().append(iddoc).append("_").append(
                    SolrConstants.FULLTEXT).toString());
            if (Files.isRegularFile(xmlFile)) {
                try {
                    String xml = FileUtils.readFileToString(xmlFile.toFile(), "UTF8");
                    doc.addField(SolrConstants.FULLTEXT, xml);

                    // Add the child doc's FULLTEXT values to the SUPERFULLTEXT value of the root doc
                    if (aggregateRecords) {
                        // sbSuperDefault.append('\n').append(doc.getFieldValue(SolrConstants.FULLTEXT));
                        rootDoc.addField(SolrConstants.SUPERFULLTEXT, (doc.getFieldValue(SolrConstants.FULLTEXT)));
                    }
                    logger.debug("Found FULLTEXT for: {}", iddoc);
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }
        checkAndAddAccessCondition(doc);
        if (!solrHelper.writeToIndex(doc)) {
            logger.error(doc.toString());
        }
        // newOrder++;
    } else {
        logger.error("Could not find serialized document for IDDOC: {}", iddoc);
    }
}
 
Example 15
Project: jbake-rtl-jalaali   File: AbstractTemplateEngineRenderingTest.java   View Source Code Vote up 5 votes
@Test
public void renderIndex() throws Exception {
    //exec
    renderer.renderIndex("index.html");

    //validate
    File outputFile = new File(destinationFolder, "index.html");
    Assert.assertTrue(outputFile.exists());

    // verify
    String output = FileUtils.readFileToString(outputFile, Charset.defaultCharset());
    for (String string : getOutputStrings("index")) {
        assertThat(output).contains(string);
    }
}
 
Example 16
Project: TOSCAna   File: PersistentAppenderTest.java   View Source Code Vote up 5 votes
@Test
public void appenderWritesStackTracesToFile() throws IOException {
    log = new LogImpl(logfile);
    logger = log.getLogger(getClass());
    try {
        throw new ArithmeticException();
    } catch (ArithmeticException e) {
        logger.error("testing stacktraces", e);
    }
    String result = FileUtils.readFileToString(logfile);
    String[] lines = result.split("\n");
    assertTrue(lines.length > 20);
}
 
Example 17
Project: atlas   File: ApkInjectInfoCreator.java   View Source Code Vote up 4 votes
private void mergeBundleInfos(AppVariantContext appVariantContext, InjectParam injectParam,
                              List<BasicBundleInfo> basicBundleInfos,
                              Map<String, BasicBundleInfo> basicBundleInfoMap) throws IOException {
    if (appVariantContext.getAtlasExtension().getTBuildConfig().isIncremental()) {
        File atlasFrameworkPropertiesFile = new File(appVariantContext.apContext.getApExploredFolder(),
                                                     "atlasFrameworkProperties.json");
        if (!atlasFrameworkPropertiesFile.exists()) {
            return;
        }
        String atlasFrameworkPropertiesStr = FileUtils.readFileToString(
            atlasFrameworkPropertiesFile);
        FrameworkProperties atlasFrameworkProperties = JSON.parseObject(
            atlasFrameworkPropertiesStr,
            FrameworkProperties.class);
        List<BasicBundleInfo> baseBundleInfos = atlasFrameworkProperties.bundleInfo;
        for (BasicBundleInfo baseBundleInfo : baseBundleInfos) {
            BasicBundleInfo basicBundleInfo = basicBundleInfoMap.get(baseBundleInfo.getPkgName());
            if (basicBundleInfo == null) {
                basicBundleInfos.add(baseBundleInfo);
                continue;
            }
            if (!baseBundleInfo.getActivities().isEmpty()) {
                basicBundleInfo.setActivities(concatList(baseBundleInfo.getActivities(),
                                                         basicBundleInfo.getActivities()));
            }
            if (!baseBundleInfo.getContentProviders().isEmpty()) {
                basicBundleInfo.setContentProviders(concatList(baseBundleInfo.getContentProviders(),
                                                               basicBundleInfo.getContentProviders()));
            }
            if (!baseBundleInfo.getDependency().isEmpty()) {
                basicBundleInfo.setDependency(concatList(baseBundleInfo.getDependency(),
                                                         basicBundleInfo.getDependency()));
            }
            if (!baseBundleInfo.getReceivers().isEmpty()) {
                basicBundleInfo.setReceivers(concatList(baseBundleInfo.getReceivers(),
                                                        basicBundleInfo.getReceivers()));
            }
            if (!baseBundleInfo.getServices().isEmpty()) {
                basicBundleInfo.setServices(concatList(baseBundleInfo.getServices(),
                                                       basicBundleInfo.getServices()));
            }

            if(!baseBundleInfo.getRemoteFragments().isEmpty()){
                basicBundleInfo.getRemoteFragments().putAll(baseBundleInfo.getRemoteFragments());
            }
            if(!baseBundleInfo.getRemoteViews().isEmpty()){
                basicBundleInfo.getRemoteViews().putAll(baseBundleInfo.getRemoteViews());
            }
            if(!baseBundleInfo.getRemoteTransactors().isEmpty()){
                basicBundleInfo.getRemoteTransactors().putAll(baseBundleInfo.getRemoteTransactors());
            }
        }
        injectParam.bundleInfo = JSON.toJSONString(basicBundleInfos);
        injectParam.autoStartBundles = atlasFrameworkProperties.autoStartBundles;
        injectParam.preLaunch = atlasFrameworkProperties.preLaunch;
    }
}
 
Example 18
Project: GeneratePasswordWithOneKey   File: Util.java   View Source Code Vote up 4 votes
private void securityOperation(String filePath, boolean cover, SecurityOperation operation) throws Exception {
    File file = FileUtils.getFile(filePath);
    Collection<File> files;
    if (file.exists()) {
        if (file.isDirectory()) {
            files = FileUtils.listFiles(file, LEGAL_EXTENSION, true);
        } else if (file.isFile()) {
            files = Collections.singletonList(file);
        } else {
            System.err.println("Invalid file or directory");
            return;
        }
    } else {
        System.err.println("Current os is " + SystemUtils.OS_NAME + " and " + filePath + " not exists");
        return;
    }
    for (File f : files) {
        String fileContent = FileUtils.readFileToString(f, StandardCharsets.UTF_8);
        final boolean isBase64 = Base64.isBase64(fileContent);
        // 防止一个文件多次被编码
        if (isBase64 && operation == SecurityOperation.ENCODE) {
            System.out.println(f.getName() + "是Base64编码,忽略加密操作...");
        } else if (!isBase64 && operation == SecurityOperation.DECODE) {
            System.out.println(f.getName() + "是明文文件,忽略解密操作...");
        } else {
            String transformString;
            switch (operation) {
                case DECODE:
                    transformString = decode(fileContent);
                    break;
                case ENCODE:
                    transformString = encode(fileContent);
                    break;
                default:
                    System.err.println("not have this security operation");
                    return;
            }
            if (cover) {
                FileUtils.writeStringToFile(f, transformString, StandardCharsets.UTF_8);
                System.out.println(f.getPath() + " 操作完成");
            } else {
                String bakFilePath = f.getAbsolutePath() + ".bak";
                File bakFile = FileUtils.getFile(bakFilePath);
                FileUtils.writeStringToFile(bakFile, transformString, StandardCharsets.UTF_8);
                System.out.println("创建" + bakFile.getPath() + " 操作完成");
            }
        }
    }
}
 
Example 19
Project: OCast-Java   File: PayloadTest.java   View Source Code Vote up 4 votes
@Test(expected = JSONException.class)
public void decodeWithInvalidType() throws Exception {
    File inputFile = new File(classLoader.getResource("eventInvalidType.json").getFile());
    String input = FileUtils.readFileToString(inputFile, Charset.defaultCharset());
    Payload.decode(input);
}
 
Example 20
Project: WebPLP   File: FileUtil.java   View Source Code Vote up 4 votes
public static String readAllLines(File file) throws IOException
{
	return FileUtils.readFileToString(file);
}