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

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

Introduction

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

Prototype

public static void writeStringToFile(File file, String data) throws IOException 

Source Link

Document

Writes a String to a file creating the file if it does not exist using the default encoding for the VM.

Usage

From source file:com.beaconhill.yqd.Processor.java

public void download(String dataDir, List<String> symbols) {
    try {/*w ww  . java  2 s. co m*/
        Downloader d = new Downloader();
        for (String s : symbols) {
            String fileName = dataDir + "/" + s + ".csv";
            String data = d.getSymbolData(s);
            if (data.startsWith("<!doctype html")) {
                System.err.println("ERROR: not found " + s);
            } else {
                FileUtils.writeStringToFile(new File(fileName), data);
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }

}

From source file:com.ikon.servlet.TextToSpeechServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    String cmd = "espeak -v mb-es1 -f input.txt | mbrola -e /usr/share/mbrola/voices/es1 - -.wav "
            + "| oggenc -Q - -o output.ogg";
    String text = WebUtils.getString(request, "text");
    String docPath = WebUtils.getString(request, "docPath");
    response.setContentType("audio/ogg");
    FileInputStream fis = null;/*w w w .  j av a  2  s.  co m*/
    OutputStream os = null;

    try {
        if (!text.equals("")) {
            FileUtils.writeStringToFile(new File("input.txt"), text);
        } else if (!docPath.equals("")) {
            InputStream is = OKMDocument.getInstance().getContent(null, docPath, false);
            Document doc = OKMDocument.getInstance().getProperties(null, docPath);
            DocConverter.getInstance().doc2txt(is, doc.getMimeType(), new File("input.txt"));
        }

        // Convert to voice
        ProcessBuilder pb = new ProcessBuilder("/bin/sh", "-c", cmd);
        Process process = pb.start();
        process.waitFor();
        String info = IOUtils.toString(process.getInputStream());
        process.destroy();

        if (process.exitValue() == 1) {
            log.warn(info);
        }

        // Send to client
        os = response.getOutputStream();
        fis = new FileInputStream("output.ogg");
        IOUtils.copy(fis, os);
        os.flush();
    } catch (InterruptedException e) {
        log.warn(e.getMessage(), e);
    } catch (IOException e) {
        log.warn(e.getMessage(), e);
    } catch (PathNotFoundException e) {
        log.warn(e.getMessage(), e);
    } catch (AccessDeniedException e) {
        log.warn(e.getMessage(), e);
    } catch (RepositoryException e) {
        log.warn(e.getMessage(), e);
    } catch (DatabaseException e) {
        log.warn(e.getMessage(), e);
    } catch (ConversionException e) {
        log.warn(e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(fis);
        IOUtils.closeQuietly(os);
    }
}

From source file:com.metadave.stow.Stow.java

public static void generateObjects(String groupFile, String classPackage, String classPrefix, String dest) {
    if (classPrefix == null) {
        classPrefix = "";
    }/* w  w  w.j a v a  2s.c  om*/

    Set<String> templateNames = new HashSet<String>();
    StowSTGroupFile stg = new StowSTGroupFile(groupFile);
    STGroup outputGroup = new STGroupFile("Stow.stg");

    Map<String, CompiledST> ts = stg.getTemplates();
    int i = 1;
    for (String s : ts.keySet()) {
        CompiledST t = ts.get(s);
        if (t.isAnonSubtemplate) {
            continue;
        }
        String templateId;

        if (!templateNames.contains(t.name.toUpperCase())) {
            templateNames.add(t.name.toUpperCase());
            templateId = t.name;
        } else {
            System.out.println("Adding a unique id to " + t.name);
            templateId = t.name + i;
        }

        STOWSTBean bean = new STOWSTBean(outputGroup);
        bean.addPackage(classPackage);
        bean.addTemplateName(t.name);
        String className = classPrefix + templateId;
        bean.addBeanClass(className);
        if (t.hasFormalArgs) {
            Map<String, FormalArgument> fas = t.formalArguments;
            if (fas != null) {
                for (String fa : fas.keySet()) {
                    FormalArgument f = fas.get(fa);
                    STOWSTAccessor acc = new STOWSTAccessor(outputGroup);
                    acc.addBeanClass(className);
                    acc.addMethodName(getNiceName(f.name));
                    acc.addParamName(f.name);
                    bean.addAccessor(acc);
                }
            }
        }

        String outputFileName = dest + File.separator + className + ".java";
        System.out.println("Generating " + outputFileName);
        File f = new File(outputFileName);

        try {
            FileUtils.writeStringToFile(f, bean.getST().render());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    System.out.println("Finished!");
}

From source file:es.uvigo.ei.sing.adops.operations.running.codeml.CodeMLDefaultProcessManager.java

@Override
public void createNexusFile(File fastaFile, File nexusFile) throws OperationException {
    DefaultFactory factory = new DefaultFactory();
    Reader fastaReader = factory.getReader("linux", "clustal", "fasta", false, "logger");
    Writer nexusWriter = factory.getWriter("linux", "paml", "nexus", false, false, true, false, "logger");

    String fastaString;//from w  w w.  j  av a 2  s . com
    try {
        fastaString = FileUtils.readFileToString(fastaFile);
    } catch (IOException e) {
        throw new OperationException(null, "Error reading input fasta file", e);
    }
    try {
        FileUtils.writeStringToFile(nexusFile, nexusWriter.write(fastaReader.read(fastaString)));
    } catch (IOException e) {
        throw new OperationException(null, "Error creating nexus file", e);
    } catch (ParseException e) {
        throw new OperationException(null, "Error parsing fasta file", e);
    }
}

From source file:com.galenframework.api.PageDump.java

public void exportAsHtml(String title, File file) throws IOException {
    makeSureFileExists(file);//from w  w  w.  j  a v  a 2  s .  c o m
    ObjectMapper objectMapper = new ObjectMapper();
    String jsonText = objectMapper.writeValueAsString(this);

    String template = IOUtils.toString(getClass().getResourceAsStream("/pagedump/page.html"));

    String htmlText = template.replace("${title}", title);
    htmlText = htmlText.replace("${json}", jsonText);

    FileUtils.writeStringToFile(file, htmlText);
}

From source file:com.galenframework.ide.services.profiles.ProfilesServiceImpl.java

@Override
public void saveProfile(String path) {
    File profileFile = new File(path);
    ProfileContent profileContent = new ProfileContent();
    profileContent.setSettings(serviceProvider.settingsService().getSettings());
    profileContent.setDevices(serviceProvider.deviceService().getAllDevices().stream()
            .map(Device::toDeviceRequest).collect(Collectors.toList()));

    try {//from   ww w .ja v  a2  s  . c  o m
        FileUtils.writeStringToFile(profileFile, objectMapper.writeValueAsString(profileContent));
    } catch (IOException e) {
        throw new RuntimeException("Error during saving profile", e);
    }
}

From source file:de.tudarmstadt.ukp.dkpro.tc.fstore.simple.SparseFeatureStoreTest.java

@Test
public void testSerializeJSON() throws Exception {
    Gson gson = new Gson();
    File tmpFile = File.createTempFile("tempFeatureStore", ".json");
    FileUtils.writeStringToFile(tmpFile, gson.toJson(featureStore));

    // make sure we have correctly filled instance
    testValuesOfDefaultFeatureStoreInstance(featureStore);

    FeatureStore fs = gson.fromJson(FileUtils.readFileToString(tmpFile), SparseFeatureStore.class);

    // test deserialized values
    testValuesOfDefaultFeatureStoreInstance(fs);

    FileUtils.deleteQuietly(tmpFile);/* w  ww  . jav a  2 s . co  m*/
}

From source file:fm.last.citrine.service.LogFileManagerTest.java

@Test
public void testDeleteBefore() throws IOException, InterruptedException {
    logFileManager = new LogFileManagerImpl(tempFolder.getRoot().getAbsolutePath());
    File logFile1 = tempFolder.newFile("1.log");
    FileUtils.writeStringToFile(logFile1, "bla");
    File otherFile1 = tempFolder.newFile("1.bla");
    FileUtils.writeStringToFile(otherFile1, "bla");
    Thread.sleep(4000);//w ww . j av  a2  s.  co  m
    DateTime cutoff = new DateTime();
    Thread.sleep(1000);
    File logFile2 = tempFolder.newFile("2.log");
    FileUtils.writeStringToFile(logFile2, "bla");
    logFileManager.deleteBefore(cutoff);

    // make sure only older file (logFile1) was deleted
    List<String> logFiles = logFileManager.findAllLogFiles();
    assertEquals(1, logFiles.size());
    assertEquals(logFile2.getName(), logFiles.get(0));

    // make sure non-log file was not deleted
    File[] files = tempFolder.getRoot().listFiles();
    assertEquals(2, files.length);
    for (File file : files) {
        String fileName = file.getName();
        assertTrue(fileName.equals(logFile2.getName()) || fileName.equals(otherFile1.getName()));
    }
}

From source file:fm.last.commons.test.LastAssertionsTest.java

@Test(expected = java.lang.AssertionError.class)
public void assertFilesEqualWithDifferentFilesOneLargerThanMessageThreshold() throws IOException {
    File file1 = new File(dataFolder.getFolder(), "file1.txt");
    File largeFile = temporaryFolder.newFile("largeFile.txt");
    FileUtils.writeStringToFile(largeFile,
            RandomStringUtils.randomAscii((int) JedecByteUnit.MEGABYTES.toBytes(1.1)));
    LastAssertions.assertFileEquals(file1, largeFile);
}

From source file:fr.paris.lutece.plugins.seo.service.sitemap.SitemapService.java

/**
 * Generate Sitemap//from   w ww.  ja v a2 s .  c  o m
 * @return The sitemap content
 */
public static String generateSitemap() {
    List<FriendlyUrl> list = getSitemapUrls();
    Map<String, Object> model = new HashMap<String, Object>();

    model.put(MARK_URLS_LIST, list);

    HtmlTemplate templateList = AppTemplateService.getTemplate(TEMPLATE_SITEMAP_XML, Locale.getDefault(),
            model);

    String strXmlSitemap = templateList.getHtml();
    String strSiteMapFilePath = AppPathService.getWebAppPath() + FILE_SITEMAP;
    File fileSiteMap = new File(strSiteMapFilePath);

    String strResult = "OK";

    try {
        FileUtils.writeStringToFile(fileSiteMap, strXmlSitemap);
    } catch (IOException e) {
        AppLogService.error("Error writing Sitemap file : " + e.getMessage(), e.getCause());
        strResult = "Error : " + e.getMessage();
    }

    String strDate = DateFormat.getDateTimeInstance().format(new Date());
    Object[] args = { strDate, list.size(), strResult };
    String strLogFormat = I18nService.getLocalizedString(PROPERTY_SITEMAP_LOG, Locale.getDefault());
    String strLog = MessageFormat.format(strLogFormat, args);
    DatastoreService.setDataValue(SEODataKeys.KEY_SITEMAP_UPDATE_LOG, strLog);

    return strLog;
}