List of usage examples for java.io FileWriter flush
public void flush() throws IOException
From source file:bridge.toolkit.commands.SCOBuilder.java
/** * Builds an unique htm file for each 'resource' element that has * scormType = 'sco' found in the imsmanifest.xml file. * /*from ww w .j a v a 2s . c o m*/ * @param scoNum * @throws IOException */ public void buildHTMLFile(int scoNum) throws IOException { String num = Integer.toString(scoNum); Element html = new Element("html"); Element head = new Element("head"); Element script = new Element("script"); List<Attribute> scriptAtts = new ArrayList<Attribute>(); scriptAtts.add(new Attribute("language", "javascript")); scriptAtts.add(new Attribute("src", "../s1000d/app/navScript.js")); script.setAttributes(scriptAtts); script.addContent("/* */"); head.addContent(script); html.addContent(head); Element frameset = new Element("frameset"); List<Attribute> framesetAtts = new ArrayList<Attribute>(); framesetAtts.add(new Attribute("id", "toolkit")); framesetAtts.add(new Attribute("rows", "43,*,35")); frameset.setAttributes(framesetAtts); Element topframe = new Element("frame"); List<Attribute> topframeAtts = new ArrayList<Attribute>(); topframeAtts.add(new Attribute("id", "topframe")); topframeAtts.add(new Attribute("name", "topframe")); topframeAtts.add(new Attribute("src", "../s1000d/app/topz.htm")); topframeAtts.add(new Attribute("scrolling", "no")); topframeAtts.add(new Attribute("frameborder", "0")); topframeAtts.add(new Attribute("marginheight", "1")); topframe.setAttributes(topframeAtts); Element content = new Element("frame"); List<Attribute> contentAtts = new ArrayList<Attribute>(); contentAtts.add(new Attribute("id", "content")); contentAtts.add(new Attribute("name", "content")); contentAtts.add(new Attribute("src", "../s1000d/app/content.htm")); contentAtts.add(new Attribute("scrolling", "auto")); contentAtts.add(new Attribute("frameborder", "0")); content.setAttributes(contentAtts); Element navframe = new Element("frame"); List<Attribute> navframeAtts = new ArrayList<Attribute>(); navframeAtts.add(new Attribute("id", "nav_frame")); navframeAtts.add(new Attribute("name", "nav_frame")); navframeAtts.add(new Attribute("src", "../s1000d/app/navPage.htm?loc=" + num)); navframeAtts.add(new Attribute("frameborder", "0")); navframe.setAttributes(navframeAtts); frameset.addContent(topframe); frameset.addContent(content); frameset.addContent(navframe); html.addContent(frameset); File scoFolder = new File(cpPackage + File.separator + "resources/scos/"); scoFolder.mkdir(); XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat()); FileWriter writer = new FileWriter(cpPackage + File.separator + "resources/scos/index" + num + ".htm"); outputter.output(html, writer); writer.flush(); writer.close(); }
From source file:com.nimbits.server.io.BlobStoreImpl.java
private void writeFile(ValueBlobStoreEntity store, String json) { FileWriter out; try {// w w w . j a v a 2 s . co m String path = getPath(store); File file = new File(path); file.getParentFile().mkdirs(); out = new FileWriter(file); out.write(json); out.flush(); out.close(); } catch (IOException ex) { logger.log(Level.SEVERE, "Error writing file", ex); } }
From source file:au.org.ala.spatial.analysis.layers.LayerDistanceIndex.java
public void run() { FileWriter fw = null; try {/*from w w w. j av a 2s . c o m*/ fw = new FileWriter(filename, true); try { while (true) { String s = toDisk.take(); fw.append(s + "\n"); fw.flush(); } } catch (Exception e) { //This is expected to occur after all distances are //calculated and the calling of interrupt. //Might as well attempt to finish up. try { while (toDisk.size() > 0) { String s = toDisk.take(); fw.append(s + "\n"); fw.flush(); } } catch (Exception ex) { logger.error(ex.getMessage(), ex); } } } catch (IOException e) { logger.error(e.getMessage(), e); } finally { if (fw != null) { try { fw.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } }
From source file:com.goeuro.goeurotest.service.Services.java
/** * Write CSV file using list of records and pre defined static header * * @param recordsList//www . j a v a2 s . c o m * @throws Exception */ public void writeCSV(List recordsList) throws Exception { FileWriter fileWriter = null; CSVPrinter csvFilePrinter = null; try { CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator(Defines.NEW_LINE_SEPARATOR); fileWriter = new FileWriter(Defines.FILE_NAME); csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat); csvFilePrinter.printRecord(Defines.FILE_HEADER); for (Object recordList : recordsList) { csvFilePrinter.printRecords(recordList); } fileWriter.flush(); fileWriter.close(); csvFilePrinter.close(); } catch (IOException ex) { throw new Exception("IOException occured while writing CSV file " + ex.getMessage()); } }
From source file:Fetcher.Fetcher.java
@Deprecated @Override/*from w ww. ja va 2s . c om*/ /** * run() is deprecated. Use startFetching() instead. */ public void run() { WebDocument link = null; HttpURLConnection connection; Proxy p; //PreConnfiguration //Configure proxy //TODO Anonymizer is deprecated. Use in following for warning generation. switch (Variables.anonymizerProxyType) { case DIRECT: p = new Proxy(Proxy.Type.DIRECT, new InetSocketAddress(Variables.anonymizerIP, Variables.anonymizerPort)); break; case HTTP: p = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(Variables.anonymizerIP, Variables.anonymizerPort)); break; case SOCKS: p = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(Variables.anonymizerIP, Variables.anonymizerPort)); break; case NONE: default: p = null; break; } link = Methods.getNextProfileLink(); while (link != null && isWorking) { //Start fetching ... //Check if it should work or not Date currentTime = Methods.getCurrentTime(); if (!currentTime.after(Variables.startTime) || !currentTime.before(Variables.endTime)) { try { synchronized (t) { getThread().wait(60000); //sleep 60 seconds } } catch (InterruptedException ex) { if (Variables.debug) { Variables.logger.Log(Fetcher.class, Variables.LogType.Error, "Time is not between start and end time and thread is in exception!"); } } finally { continue; } } String URL = link.getNextUrl(); String UA = Methods.getRandomUserAgent(); //Use this UA for refererd or single links. //loop for referer for (int i = 0; i <= link.getRefererCount(); URL = link.getNextUrl(), i++) { if (Variables.debug && Variables.vv) { Variables.logger.Log(Fetcher.class, Variables.LogType.Trace, "Fetcher (" + Methods.Colorize(name, Methods.Color.Green) + ") start getting " + URL); } try { //Anonymizer if (Variables.anonymizerProxyType == Variables.AnonymizerProxy.NONE) { connection = (HttpURLConnection) new URL(URL).openConnection(); } else { connection = (HttpURLConnection) new URL(URL).openConnection(p); } connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestProperty("User-Agent", UA); connection.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); connection.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); connection.setRequestProperty("Accept-Encoding", "gzip, deflated"); String referer = link.getNextReferrer(); if (referer != null) { connection.setRequestProperty("Referer", referer); referer = null; System.gc(); } //Send Cookie using user input if (!(Variables.Cookie == null || Variables.Cookie.equalsIgnoreCase(""))) { connection.setRequestProperty("Cookie", Variables.Cookie); } else if (cookies.getCookieStore().getCookies().size() > 0) { //From referer, there are some cookies connection.setRequestProperty("Cookie", Join(",", cookies.getCookieStore().getCookies())); } connection.setRequestMethod("GET"); connection.connect(); //Get Cookie from response getCookies(connection); if (connection.getResponseCode() == 200) { //Write to file String outputName = Variables.outputDirectory + link.getOutputName().substring(0, link.getOutputName().lastIndexOf(".")) + i + link.getOutputName().substring(link.getOutputName().lastIndexOf(".")); //Check extension if (!(outputName.endsWith("html") || outputName.endsWith("htm"))) { outputName += "html"; } //get content String html = ""; if (connection.getContentEncoding().equalsIgnoreCase("gzip")) { html = IOUtils.toString(new GZIPInputStream(connection.getInputStream())); } else if (connection.getContentEncoding().equalsIgnoreCase("deflate")) { html = IOUtils.toString(new InflaterInputStream(connection.getInputStream())); } FileWriter fw = new FileWriter(outputName); fw.write(html); fw.flush(); fw.close(); } else { //The returned code is not 200. if (Variables.debug) { Variables.logger.Log(Fetcher.class, Variables.LogType.Error, "Fetcher could not download (" + Methods.Colorize(URL, Methods.Color.Red) + ") in " + name); if (Variables.vv) { Variables.logger.Log(Fetcher.class, Variables.LogType.Error, "Server responded (" + Methods.Colorize(connection.getResponseCode() + " - " + connection.getResponseMessage(), Methods.Color.Red) + ") for " + URL); } } } //Close the connection connection.disconnect(); //Report progress Variables.logger.logResult(connection, link); Methods.oneFinished(); if (Variables.debug && Variables.vv) { Variables.logger.Log(Fetcher.class, Variables.LogType.Info, "[+] Done fetching (" + Methods.Colorize(URL, Methods.Color.Red) + "]"); } try { synchronized (t) { t.wait(Methods.getNextRandom() * 1000); } } catch (InterruptedException ex) { if (Variables.debug) { Variables.logger.Log(Fetcher.class, Variables.LogType.Error, "Cannot interrupt thread [" + Methods.Colorize(name, Methods.Color.Red) + "]. Interrupted before!"); } } catch (IllegalArgumentException ex) { if (Variables.debug) { Variables.logger.Log(Fetcher.class, Variables.LogType.Error, "-1 is returned as random number for thread [" + Methods.Colorize(name, Methods.Color.Red) + "]."); } } } catch (IOException ex) { if (Variables.debug) { if (Variables.vv) { Variables.logger.Log(Fetcher.class, Variables.LogType.Error, "Error in fetching [" + Methods.Colorize(URL, Methods.Color.Red) + "] in fetcher (" + Methods.Colorize(name, Methods.Color.Yellow) + ") for writing in (" + Methods.Colorize(link.getOutputName(), Methods.Color.White) + "). Detail:\r\n" + ex.getMessage()); } else { Variables.logger.Log(Fetcher.class, Variables.LogType.Error, "Error in fetching [" + Methods.Colorize(URL, Methods.Color.Red) + "]"); } } } catch (NullPointerException ex) { //Thrown sometimes and make the thread as Dead! if (Variables.debug) { if (Variables.vv) { Variables.logger.Log(Fetcher.class, Variables.LogType.Error, "Null pointer occured. Error in fetching [" + Methods.Colorize(URL, Methods.Color.Red) + "] in fetcher (" + Methods.Colorize(name, Methods.Color.Yellow) + ") for writing in (" + Methods.Colorize(link.getOutputName(), Methods.Color.White) + ")."); } else { Variables.logger.Log(Fetcher.class, Variables.LogType.Error, "Null pointer occured. Error in fetching [" + Methods.Colorize(URL, Methods.Color.Red) + "]"); } } } } //Check size limit and compress ... long size = Methods.getFolderSize(Variables.outputDirectory); if (size >= Variables.outputSizeLimit) { //Deactivate itself by waiting ... Variables.state = Variables.microbotState.Compressing; Variables.threadController.changeActiveThreads(false, t, Variables.microbotState.Compressing); } //Check if user terminated program or not if (isWorking) { link = Methods.getNextProfileLink(); } } //Thread finished. (Normally or by force) Variables.state = Variables.microbotState.Stopping; Variables.threadController.changeActiveThreads(false, t, Variables.microbotState.Stopping); //URLs done. This thread finishes its work. if (Variables.debug) { Variables.logger.Log(Fetcher.class, Variables.LogType.Info, "Fetcher (" + Methods.Colorize(name, Methods.Color.Green) + ") finished its work."); } }
From source file:it.readbeyond.minstrel.commander.Commander.java
private String writeStringToFile(String path, String contents) { try {/* w w w .j a v a 2 s .co m*/ // TODO check for write permission? File f = new File(this.normalizePath(path)); FileWriter out = new FileWriter(f); out.write(contents); out.flush(); out.close(); return MESSAGE_FILE_WRITTEN; } catch (Exception e) { // nop } return MESSAGE_FILE_NOT_WRITTEN; }
From source file:com.cyberway.issue.crawler.framework.CrawlScope.java
/** * Add a new seed to scope. By default, simply appends * to seeds file, though subclasses may handle differently. * * <p>This method is *not* sufficient to get the new seed * scheduled in the Frontier for crawling -- it only * affects the Scope's seed record (and decisions which * flow from seeds). // w w w . j av a 2s . c o m * * @param curi CandidateUri to add * @return true if successful, false if add failed for any reason */ public boolean addSeed(final CandidateURI curi) { File f = getSeedfile(); if (f != null) { try { FileWriter fw = new FileWriter(f, true); // Write to new (last) line the URL. fw.write("\n"); fw.write("# Heritrix added seed " + ((curi.getVia() != null) ? "redirect from " + curi.getVia() : "(JMX)") + ".\n"); fw.write(curi.toString()); fw.flush(); fw.close(); Iterator iter = seedListeners.iterator(); while (iter.hasNext()) { ((SeedListener) iter.next()).addedSeed(curi); } return true; } catch (IOException e) { DevUtils.warnHandle(e, "problem writing new seed"); } } return false; }
From source file:com.bigtester.ate.tcg.controller.TrainingFileDB.java
/** * Write test csv file./*from ww w . ja va 2 s .c o m*/ * * @param mlInputs * the ml inputs * @param append * the append * @throws IOException */ public static void writeTestCsvFile(List<String> mlInputs, boolean append) throws IOException { if (mlInputs.isEmpty()) return; // Create new students objects List<UserInputTrainingRecord> trainings = new ArrayList<UserInputTrainingRecord>(); for (int index = 0; index < mlInputs.size(); index++) { String temp = mlInputs.get(index); if (null != temp) { trainings.add(new UserInputTrainingRecord(" ", temp)); } } FileWriter fileWriter = null; // NOPMD CSVPrinter csvFilePrinter = null; // NOPMD // Create the CSVFormat object with "\n" as a record delimiter CSVFormat csvFileFormat = getCSVFormat(); try { // initialize FileWriter object // FileSystemResource testFile = new // FileSystemResource(UserInputsTrainer.TESTFILE); fileWriter = new FileWriter(UserInputsTrainer.TESTFILE, append); // initialize CSVPrinter object csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);// NOPMD // Write a new student object list to the CSV file for (UserInputTrainingRecord student : trainings) { List<String> studentDataRecord = new ArrayList<String>(); studentDataRecord.add(student.getInputLabelName()); studentDataRecord.add(student.getInputMLHtmlCode()); csvFilePrinter.printRecord(studentDataRecord); } // System.out.println("CSV file was created successfully !!!"); } catch (Exception e) {// NOPMD throw new IOException("Error in CsvFileWriter !!!");// NOPMD // e.printStackTrace(); } finally {// NOPMD try { if (null != fileWriter) { fileWriter.flush(); fileWriter.close(); } if (null != csvFilePrinter) { csvFilePrinter.close(); } } catch (IOException e) { // NOPMD throw new IOException(//NOPMD "Error while flushing/closing fileWriter/csvPrinter !!!"); // NOPMD // e.printStackTrace(); } } }
From source file:jp.tricreo.codegenerator.service.impl.CodeGenStrategyForFreeMarker.java
@Override public void generate(CodeGenContext codeGenContext) throws CodeGenException { Validate.notNull(codeGenContext);/*from www . ja v a2 s . c o m*/ File templateDirFile = codeGenContext.getTemplateDir(); Configuration cfg = new Configuration(); try { cfg.setDirectoryForTemplateLoading(templateDirFile); Template template = cfg.getTemplate(TEMPLATE_FILENAME); for (ClassMetaModel classMetaModel : codeGenContext.getClassMetaModels()) { FileWriter fw = null; try { Map<String, Object> rootMap = new HashMap<String, Object>(); rootMap.put("classMetaModel", classMetaModel); File exportClassDir = getExportClassDir(codeGenContext, classMetaModel); exportClassDir.mkdirs(); fw = new FileWriter( new File(exportClassDir, classMetaModel.getClassName() + "." + GENERATE_FILE_EXT)); template.process(rootMap, fw); fw.flush(); LOGGER.info("????? : {}", classMetaModel.getClassName()); } catch (TemplateException ex) { throw new CodeGenException(ex); } finally { IOUtils.closeQuietly(fw); /* IOUtils#closeQuietly??????? try { if (fw != null) { fw.close(); } } catch (IOException ioe) { // ignore } */ } } } catch (IOException ex) { throw new CodeGenException(ex); } }
From source file:com.manydesigns.portofino.pageactions.AbstractPageAction.java
protected void updateScript() { File directory = pageInstance.getDirectory(); File groovyScriptFile = ScriptingUtil.getGroovyScriptFile(directory, "action"); FileWriter fw = null; try {/*from ww w . j a v a 2s .c o m*/ fw = new FileWriter(groovyScriptFile); fw.write(script); fw.flush(); fw.close(); Class<?> scriptClass = DispatcherLogic.getActionClass(portofinoConfiguration, directory, false); if (scriptClass == null) { SessionMessages.addErrorMessage(ElementsThreadLocals.getText("script.class.is.not.valid")); } if (this instanceof GroovyObject) { //Attempt to remove old instance of custom action bean //not guaranteed to work try { ModelActionResolver actionResolver = (ModelActionResolver) StripesFilter.getConfiguration() .getActionResolver(); actionResolver.removeActionBean(getClass()); } catch (Exception e) { logger.warn("Couldn't remove action bean " + this, e); } } } catch (IOException e) { logger.error("Error writing script to " + groovyScriptFile, e); String msg = ElementsThreadLocals.getText("couldnt.write.script.to._", groovyScriptFile.getAbsolutePath()); SessionMessages.addErrorMessage(msg); } catch (Exception e) { String pageId = pageInstance.getPage().getId(); logger.warn("Couldn't compile script for page " + pageId, e); SessionMessages.addErrorMessage(ElementsThreadLocals.getText("couldnt.compile.script")); } finally { IOUtils.closeQuietly(fw); } }