Example usage for org.apache.commons.io FileUtils readFileToString

List of usage examples for org.apache.commons.io FileUtils readFileToString

Introduction

In this page you can find the example usage for org.apache.commons.io FileUtils readFileToString.

Prototype

public static String readFileToString(File file, String encoding) throws IOException 

Source Link

Document

Reads the contents of a file into a String.

Usage

From source file:it.drwolf.ridire.servlet.TmpResourcesServlet.java

public void getTmpFile(String filename) {
    HttpServletResponse response = (HttpServletResponse) this.extCtx.getResponse();
    response.setContentType("text/html");
    response.setCharacterEncoding("UTF-8");
    response.setHeader("Expires", "0");
    response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
    response.setHeader("Pragma", "public");
    try {/*  w  w  w  .  j a va2 s  .co m*/
        String ret = FileUtils.readFileToString(
                new File(
                        System.getProperty("java.io.tmpdir") + System.getProperty("file.separator") + filename),
                "UTF-8");
        response.getOutputStream().print(ret);
        response.getOutputStream().flush();
        // FacesContext.getCurrentInstance().responseComplete();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.xebia.mojo.dashboard.reports.html.CpdDashboardReportTest.java

public void testShouldCountCorrectNumberOfViolations() throws Exception {
    String line = FileUtils.readFileToString(testFile, null);
    int aantal = StringUtils.countMatches(line, "<th>File</th>");
    Node result = cpdDashboardReport.findNode(mavenProject, "count(//th[text()='File'])");
    assertEquals(String.valueOf(aantal), result.getText());
}

From source file:hudson.plugins.simpleupdatesite.Plugin.java

private String getExcerpt(File hpiFile) {
    try {/*from w ww  .  ja  v a2 s .co  m*/
        String baseName = FilenameUtils.getBaseName(hpiFile.getName());
        File exceptFile = new File(hpiFile.getParent(), baseName + ".info");
        if (exceptFile.exists()) {
            return FileUtils.readFileToString(exceptFile, "UTF-8");
        } else {
            return "";
        }
    } catch (Exception e) {
        return "";
    }
}

From source file:io.wcm.devops.conga.generator.plugins.fileheader.AbstractFileHeader.java

@Override
public final Void apply(FileContext file, FileHeaderContext context) {
    String lineBreak = StringUtils.defaultString(getLineBreak());
    try {// w w w  . ja  va  2  s .c  o  m
        String content = FileUtils.readFileToString(file.getFile(), file.getCharset());

        List<String> sanitizedCommentLines;
        if (context.getCommentLines() == null) {
            sanitizedCommentLines = ImmutableList.of();
        } else {
            sanitizedCommentLines = context.getCommentLines().stream().map(line -> sanitizeComment(line))
                    .filter(line -> line != null)
                    .map(line -> StringUtils.defaultString(getCommentLinePrefix()) + line + lineBreak)
                    .collect(Collectors.toList());
        }

        int insertPosition = getInsertPosition(content);

        content = StringUtils.substring(content, 0, insertPosition)
                + StringUtils.defaultString(getCommentBlockStart())
                + StringUtils.join(sanitizedCommentLines, "") + StringUtils.defaultString(getCommentBlockEnd())
                + StringUtils.defaultString(getBlockSuffix()) + StringUtils.substring(content, insertPosition);

        file.getFile().delete();
        FileUtils.write(file.getFile(), content, file.getCharset());
    } catch (IOException ex) {
        throw new GeneratorException("Unable to add file header to " + FileUtil.getCanonicalPath(file), ex);
    }
    return null;
}

From source file:com.blackducksoftware.integration.hub.detect.detector.packagist.ComposerLockExtractor.java

public Extraction extract(final File directory, final File composerJson, final File composerLock) {
    try {// w  ww .  j  av a2  s  .  co m
        final String composerJsonText = FileUtils.readFileToString(composerJson, StandardCharsets.UTF_8);
        final String composerLockText = FileUtils.readFileToString(composerLock, StandardCharsets.UTF_8);

        logger.debug(composerJsonText);
        logger.debug(composerLockText);

        final PackagistParseResult result = packagistParser.getDependencyGraphFromProject(directory.toString(),
                composerJsonText, composerLockText);

        return new Extraction.Builder().success(result.codeLocation).projectName(result.projectName)
                .projectVersion(result.projectVersion).build();
    } catch (final Exception e) {
        return new Extraction.Builder().exception(e).build();
    }
}

From source file:com.ppcxy.cyfm.showcase.demos.utilities.io.IODemo.java

@Test
public void workWithFileContent() {
    File file = new File("woop.txt");
    File destFile = new File("bar.txt");
    try {/*  w ww .  j  a  v  a 2  s.  co  m*/
        // text -> file, Collection<String>, byte[] ->file
        FileUtils.writeStringToFile(file, "Hey sailor!\nHaha\n", "UTF-8");

        // inputstream -> file
        InputStream source = IOUtils.toInputStream("Hej", "UTF-8");
        FileUtils.copyInputStreamToFile(source, file);

        // ///////////////////////////
        // file -> outputstream
        System.out.println("copy File to outputstream:");
        FileUtils.copyFile(file, System.out);

        // file -> file
        FileUtils.copyFile(file, destFile);

        // file -> string
        System.out.println("File to String:");
        System.out.println(FileUtils.readFileToString(file, "UTF-8"));

        // file -> list<string>
        System.out.println("File to List<String>:");
        List<String> lines = FileUtils.readLines(file, "UTF-8");
        for (String string : lines) {
            System.out.println(string);
        }
    } catch (IOException e) {
        Exceptions.unchecked(e);
    }
}

From source file:net.sf.jtmt.summarizers.SummaryAnalyzer.java

/**
 * Instantiates a new summary analyzer.//from ww  w .  j  av a2  s  .  c  om
 *
 * @throws IOException Signals that an I/O exception has occurred.
 */
public SummaryAnalyzer() throws IOException {
    String[] stopwords = filterComments(StringUtils.split(FileUtils.readFileToString(
            new File(getClass().getResource("/resources/jtmt/stopwords.txt").getFile()), "UTF-8")));
    this.stopset = StopFilter.makeStopSet(stopwords, true);
}

From source file:jsentvar.JsonReaderTest.java

/**
 * Test of reader method, of class JsonReader.
 * @throws java.io.IOException//from   w  w w.j  a v a  2  s .  c  o m
 */
@Test
public void testReader() throws IOException {
    System.out.println("JsonReader.reader");
    String inputFileName = "resources/test/text_doc0.json";
    JsonReader instance = new JsonReader();
    String expResult = FileUtils.readFileToString(new File("resources/test/doc0Result.txt"), "utf8").trim();
    HashMap<String, HashMap<Integer, Integer>> result0 = instance.reader(inputFileName);
    String result = result0.toString();
    System.out.println("Esperat:\n" + expResult);
    System.out.println("Obtingut:\n" + result);
    assertEquals(expResult, result);

}

From source file:com.gargoylesoftware.htmlunit.libraries.LibraryTestCase.java

/**
 * Loads an expectation file for the given test in the library folder.
 * TODO: use browser version specific variations too
 * @param testName the base name for the file
 * @return the content of the file// www  . ja v a 2s.c  om
 * @throws Exception in case of error
 */
protected String loadExpectation(final String testName) throws Exception {
    // TODO: check first if a file specific to current browserVersion exists first with version number then without
    final String resource = getLibraryDir() + "/" + testName + ".expected.txt";
    final URL url = getClass().getClassLoader().getResource(resource);
    assertNotNull(url);
    final File file = new File(url.toURI());

    return FileUtils.readFileToString(file, "UTF-8");
}

From source file:io.wcm.devops.conga.plugins.sling.util.ProvisioningUtil.java

/**
 * Check if given file is a sling provisioning file.
 * @param file File/*from  w  ww  .j  av a2s . com*/
 * @return true if it seems to be so
 */
public static boolean isProvisioningFile(FileContext file) {
    if (FileUtil.matchesExtension(file, FILE_EXTENSION)) {
        return true;
    }
    try {
        // check for generic txt extension and do some heuristics on the content of the file
        return FileUtil.matchesExtension(file.getFile(), TEXT_FILE_EXTENSION) && StringUtils
                .contains(FileUtils.readFileToString(file.getFile(), file.getCharset()), "[feature ");
    } catch (IOException ex) {
        return false;
    }
}