List of usage examples for java.io BufferedWriter write
public void write(int c) throws IOException
From source file:com.thalesgroup.hudson.plugins.klocwork.util.KloXMLGenerator.java
public static String GenerateXMLFromIssues(String a_host, String a_port, boolean useSSL, String a_projectname, String a_filename, BuildListener listener, String a_query, String a_user) { String kwurl = ""; if (useSSL) { kwurl = "https://" + a_host + ":" + a_port; } else {// ww w .j a va 2 s . c o m kwurl = "http://" + a_host + ":" + a_port; } listener.getLogger().println("Connecting to Klocwork Web API service... " + kwurl); KWApi KWservice = new KWApi(kwurl); try { listener.getLogger().println("creating XML document"); File outputFile = new File(a_filename); if (outputFile.exists()) { outputFile.delete(); } BufferedWriter bw = null; try { bw = new BufferedWriter(new FileWriter(outputFile)); if (outputFile.canWrite()) { //Get issues listener.getLogger().println("Retrieving Klocwork issues using kwjlib..."); listener.getLogger() .println("Sending request for project: " + a_projectname + " with query: " + a_query); ArrayList<JSONObject> issues = KWservice.search(a_projectname, a_query, null, null, null); if (issues != null) { listener.getLogger().println("Number of issues returned: " + issues.size()); bw.write( "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><errorList xmlns=\"http://www.klocwork.com/inForce/report/1.0\">"); //Iterate through issues for (JSONObject issue : issues) { if (issue != null) { try { if (issue.has("id") && issue.optString("id").length() > 0) { String id = StringEscapeUtils.escapeXml(issue.optString("id")); String file = StringEscapeUtils.escapeXml(issue.optString("file")); String method = StringEscapeUtils.escapeXml(issue.optString("method")); String code = StringEscapeUtils.escapeXml(issue.optString("code")); String message = StringEscapeUtils.escapeXml(issue.optString("message")); String status = StringEscapeUtils.escapeXml(issue.optString("status")); String state = StringEscapeUtils.escapeXml(issue.optString("state")); String owner = StringEscapeUtils.escapeXml(issue.optString("owner")); String severity = StringEscapeUtils.escapeXml(issue.optString("severity")); String severityCode = StringEscapeUtils .escapeXml(issue.optString("severityCode")); String taxonomyName = StringEscapeUtils .escapeXml(issue.optString("taxonomyName")); String url = StringEscapeUtils.escapeXml(issue.optString("url")); bw.write("<problem>"); bw.newLine(); bw.write("<problemID>" + id + "</problemID>"); bw.newLine(); bw.write("<file>" + file + "</file>"); bw.newLine(); bw.write("<method>" + method + "</method>"); bw.newLine(); bw.write("<code>" + code + "</code>"); bw.newLine(); bw.write("<message>" + message + "</message>"); bw.newLine(); bw.write("<citingStatus>" + status + "</citingStatus>"); bw.newLine(); bw.write("<state>" + state + "</state>"); bw.newLine(); bw.write("<owner>" + owner + "</owner>"); bw.newLine(); bw.write("<severity>" + severity + "</severity>"); bw.newLine(); bw.write("<severitylevel>" + severityCode + "</severitylevel>"); bw.newLine(); bw.write("<displayAs>" + severity + "</displayAs>"); bw.newLine(); bw.write("<taxonomies>"); bw.newLine(); bw.write("<taxonomy name=\"" + taxonomyName + "\" metaInf=\"\" />"); bw.newLine(); bw.write("</taxonomies>"); bw.newLine(); bw.write("<url>" + url + "</url>"); bw.newLine(); bw.write("</problem>"); bw.newLine(); } } catch (Exception e) { listener.getLogger().println("[ERROR]: " + e.getMessage()); listener.getLogger().println("\tissue: " + issue.toString()); e.printStackTrace(); } } } bw.write("</errorList>"); } else { listener.getLogger().println("ERROR: Unable to get issues from Klocwork server"); if (!KWservice.errorMessage.isEmpty()) { for (JSONObject message : KWservice.errorMessage) { listener.getLogger().println("\t" + message.toString()); } KWservice.errorMessage.clear(); } return "1"; } } else { listener.getLogger() .println("ERROR while generating XML. Could not open file for writing: " + a_filename); } } finally { if (bw != null) { bw.close(); } } } catch (IOException ioe) { listener.getLogger().println("ERROR while generating XML - IOException:" + ioe.getMessage()); return "1"; } File outputFile = new File(a_filename); if (outputFile.exists() && outputFile.length() > 0) { listener.getLogger().println("Creation of XML file complete. Closing connection to Web API."); } else { listener.getLogger().println( "Creation of XML file failed. You may have to run the kwauth command on your machine."); } return "0"; }
From source file:com.cloud.hypervisor.vmware.util.VmwareHelper.java
public static byte[] composeDiskInfo(List<Ternary<String, String, String>> diskInfo, int disksInChain, boolean includeBase) throws IOException { BufferedWriter out = null; ByteArrayOutputStream bos = new ByteArrayOutputStream(); try {/*w w w .j a v a2s . c o m*/ out = new BufferedWriter(new OutputStreamWriter(bos, "UTF-8")); out.write("disksInChain=" + disksInChain); out.newLine(); out.write("disksInBackup=" + diskInfo.size()); out.newLine(); out.write("baseDiskIncluded=" + includeBase); out.newLine(); int seq = disksInChain - 1; for (Ternary<String, String, String> item : diskInfo) { out.write(String.format("disk%d.fileName=%s", seq, item.first())); out.newLine(); out.write(String.format("disk%d.baseFileName=%s", seq, item.second())); out.newLine(); if (item.third() != null) { out.write(String.format("disk%d.parentFileName=%s", seq, item.third())); out.newLine(); } seq--; } out.newLine(); } finally { if (out != null) out.close(); } return bos.toByteArray(); }
From source file:com.piaoyou.util.FileUtil.java
/** * Write content to a fileName with the destEncoding * * @param content String/*from w ww . java2 s . c o m*/ * @param fileName String * @param destEncoding String * @throws FileNotFoundException * @throws IOException */ public static void writeFile(String content, String fileName, String destEncoding) throws FileNotFoundException, IOException { File file = null; try { file = new File(fileName); if (file.isFile() == false) { throw new IOException("'" + fileName + "' is not a file."); } if (file.canWrite() == false) { throw new IOException("'" + fileName + "' is a read-only file."); } } finally { // we don't have to close File here } BufferedWriter out = null; try { FileOutputStream fos = new FileOutputStream(fileName); out = new BufferedWriter(new OutputStreamWriter(fos, destEncoding)); out.write(content); out.flush(); } catch (FileNotFoundException fe) { log.error("Error", fe); throw fe; } catch (IOException e) { log.error("Error", e); throw e; } finally { try { if (out != null) out.close(); } catch (IOException ex) { } } }
From source file:dsfixgui.FileIO.DSFixFileController.java
/** *Writes a string to a text file//w ww .j a v a2s .c o m * * @param filePath * the path of the file to be read, including the filename * @param text * the String to be written to the file; can be more than one line. * @param overwrite * determines whether the user wants to overwrite the write file if it * already exists. If true, pre-existing file will be overwritten * @throws IIOException * if the write file already exists and the user allowed overwriting, but * the file could not be overwritten * @throws AccessDeniedException * if the write file already exists but the user didn't allow overwriting * @throws IOException * if an error occurs initializing the BufferedWriter */ public static void writeTextFile(String filePath, String text, boolean overwrite) throws IIOException, IOException, AccessDeniedException { //The file to be written File writeFile = new File(filePath); if (writeFile.exists() && overwrite) { //If file exists, try to delete it if (!writeFile.delete()) { //If file cannot be deleted, throw OIOException throw new IIOException("Could not delete pre-existing file: " + filePath); } } else if (writeFile.exists() && !overwrite) { //If file exists but is not allowed to be overwritten, throw AccessDeniedException throw new AccessDeniedException(writeFile.getPath()); } //Format each linebreak to be displayed correctly in a text file String formattedText = text.replaceAll("\n", String.format("%n")); //Initialize BufferedWriter to write string to file BufferedWriter fileWriter = new BufferedWriter(new FileWriter(writeFile)); //Write the file Scanner scanner = new Scanner(formattedText); while (scanner.hasNextLine()) { fileWriter.write(scanner.nextLine()); fileWriter.newLine(); } fileWriter.close(); }
From source file:com.vmware.bdd.utils.CommonUtil.java
public static void prettyOutputStrings(List<Object> objs, String fileName, String delimeter) throws Exception { StringBuffer buff = new StringBuffer(); if (isBlank(delimeter)) { delimeter = System.lineSeparator(); }/*from w w w . j ava 2s . c om*/ for (Object obj : objs) { if (obj != null) { String str = obj.toString(); if (!isBlank(str)) { buff.append(str).append(delimeter); } } } if (buff.length() > 0) { buff.delete(buff.length() - delimeter.length(), buff.length()); } OutputStream out = null; BufferedWriter bw = null; try { if (!isBlank(fileName)) { out = new FileOutputStream(fileName); } else { out = System.out; } bw = new BufferedWriter(new OutputStreamWriter(out, "UTF-8")); bw.write(buff.toString()); if (!isBlank(fileName)) { // [Bug 1406542] always append a newline at the end of the file bw.newLine(); } bw.flush(); } finally { if (bw != null && out != null && !(out instanceof PrintStream)) { bw.close(); out.close(); } } }
From source file:com.photon.phresco.framework.win8.util.Win8MetroCofigFileParser.java
private static void changeHellworld(ApplicationInfo info) throws PhrescoException { BufferedReader br = null;/*from w w w . j ava 2 s .c om*/ BufferedWriter bw = null; File path = new File(getProjectHome(info) + File.separator + Constants.SOURCE_DIR + File.separator + HELLOWORD_SOLUTIONFILE); File tempFile = new File( getProjectHome(info) + File.separator + Constants.SOURCE_DIR + File.separator + TEMP_FOLDER); File newFile = new File(getProjectHome(info) + File.separator + Constants.SOURCE_DIR + File.separator + HELLOWORD_SOLUTIONFILE); try { br = new BufferedReader(new FileReader(path)); bw = new BufferedWriter(new FileWriter(tempFile)); String line; while ((line = br.readLine()) != null) { if (line.contains(HELLOWORLD)) { line = line.replace(HELLOWORLD, info.getName()); } bw.write(line + NEWLINE); } } catch (Exception e) { return; } finally { Utility.closeReader(br); Utility.closeWriter(bw); } FileUtil.delete(path); tempFile.renameTo(newFile); }
From source file:com.t_oster.visicut.misc.Helper.java
public static void installInkscapeExtension() throws FileNotFoundException, IOException { File src = new File(getVisiCutFolder(), "inkscape_extension"); if (!src.exists() || !src.isDirectory()) { throw new FileNotFoundException("Not a directory: " + src); }/* w w w .j a va2 s . com*/ String profile_path = System.getenv("INKSCAPE_PORTABLE_PROFILE_DIR"); if (profile_path == null) { profile_path = System.getenv("INKSCAPE_PROFILE_DIR"); } File trg; if (profile_path != null) { trg = new File(profile_path); } else { if (isWindows()) { trg = new File(System.getenv("AppData")); } else { trg = new File(FileUtils.getUserDirectory(), ".config"); } } trg = new File(new File(trg, "inkscape"), "extensions"); if (!trg.exists() && !trg.mkdirs()) { throw new FileNotFoundException("Can't create directory: " + trg); } for (File f : src.listFiles()) { if ("visicut_export.py".equals(f.getName())) { File target = new File(trg, "visicut_export.py"); BufferedReader r = new BufferedReader(new FileReader(f)); BufferedWriter w = new BufferedWriter(new FileWriter(target)); String line = r.readLine(); while (line != null) { if ("VISICUTDIR=\"\"".equals(line)) { line = "VISICUTDIR=r\"" + getVisiCutFolder().getAbsolutePath() + "\""; } w.write(line); w.newLine(); line = r.readLine(); } w.flush(); w.close(); r.close(); } else if (f.getName().toLowerCase().endsWith("inx") || f.getName().toLowerCase().endsWith("py")) { FileUtils.copyFileToDirectory(f, trg); } } }
From source file:modnlp.capte.AlignerUtils.java
public static void writeAlignment(String sourcename, Vector<Object[]> d) { //Output the current alignment as a tab separated file String sp = ""; BufferedWriter pw; try {/*from w w w. j a va 2 s. c o m*/ pw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(sourcename), "UTF-8")); //PrintWriter tp = new PrintWriter(new OutputStreamWriter(new FileOutputStream(targetname),"UTF8")); String source = ""; String target = ""; Object[] stemp; for (int i = 0; i < d.size(); i++) { stemp = d.get(i); source = (String) stemp[0]; target = (String) stemp[1]; source = clean(source); target = clean(target); sp += source + "\t" + target + "\n"; } pw.write(new String(UnicodeUtil.convert(sp.getBytes(), "UTF-8"))); pw.close(); //return sp; } catch (Exception e) { e.printStackTrace(); } }
From source file:org.eclipselabs.garbagecat.Main.java
/** * Create Garbage Collection Analysis report. * /* w ww .ja v a 2s .c o m*/ * TODO: Move to JvmRun to facilitate testing. * * @param jvmRun * JVM run data. * @param reportFileName * Report file name. * @param version * Whether or not to report garbagecat version. * @param latestVersion * Whether or not to report latest garbagecat version. * */ public static void createReport(JvmRun jvmRun, String reportFileName, boolean version, boolean latestVersion) { File reportFile = new File(reportFileName); FileWriter fileWriter = null; BufferedWriter bufferedWriter = null; try { fileWriter = new FileWriter(reportFile); bufferedWriter = new BufferedWriter(fileWriter); if (version || latestVersion) { bufferedWriter.write("========================================" + Constants.LINE_SEPARATOR); if (version) { bufferedWriter.write( "Running garbagecat version: " + getVersion() + System.getProperty("line.separator")); } if (latestVersion) { bufferedWriter.write("Latest garbagecat version/tag: " + getLatestVersion() + System.getProperty("line.separator")); } } // Bottlenecks List<String> bottlenecks = jvmRun.getBottlenecks(); if (bottlenecks.size() > 0) { bufferedWriter.write("========================================" + Constants.LINE_SEPARATOR); bufferedWriter.write( "Throughput less than " + jvmRun.getThroughputThreshold() + "%" + Constants.LINE_SEPARATOR); bufferedWriter.write("----------------------------------------" + Constants.LINE_SEPARATOR); Iterator<String> iterator = bottlenecks.iterator(); while (iterator.hasNext()) { bufferedWriter.write(iterator.next() + Constants.LINE_SEPARATOR); } } // JVM information if (jvmRun.getJvm().getVersion() != null || jvmRun.getJvm().getOptions() != null || jvmRun.getJvm().getMemory() != null) { bufferedWriter.write("========================================" + Constants.LINE_SEPARATOR); bufferedWriter.write("JVM:" + Constants.LINE_SEPARATOR); bufferedWriter.write("----------------------------------------" + Constants.LINE_SEPARATOR); if (jvmRun.getJvm().getVersion() != null) { bufferedWriter.write("Version: " + jvmRun.getJvm().getVersion() + Constants.LINE_SEPARATOR); } if (jvmRun.getJvm().getOptions() != null) { bufferedWriter.write("Options: " + jvmRun.getJvm().getOptions() + Constants.LINE_SEPARATOR); } if (jvmRun.getJvm().getMemory() != null) { bufferedWriter.write("Memory: " + jvmRun.getJvm().getMemory() + Constants.LINE_SEPARATOR); } } // Summary bufferedWriter.write("========================================" + Constants.LINE_SEPARATOR); bufferedWriter.write("SUMMARY:" + Constants.LINE_SEPARATOR); bufferedWriter.write("----------------------------------------" + Constants.LINE_SEPARATOR); // GC stats bufferedWriter.write("# GC Events: " + jvmRun.getBlockingEventCount() + Constants.LINE_SEPARATOR); if (jvmRun.getBlockingEventCount() > 0) { bufferedWriter.write("Event Types: "); List<LogEventType> eventTypes = jvmRun.getEventTypes(); Iterator<LogEventType> iterator = eventTypes.iterator(); boolean firstEvent = true; while (iterator.hasNext()) { LogEventType eventType = iterator.next(); // Only report GC events if (JdkUtil.isReportable(eventType)) { if (!firstEvent) { bufferedWriter.write(", "); } bufferedWriter.write(eventType.toString()); firstEvent = false; } } bufferedWriter.write(Constants.LINE_SEPARATOR); // Inverted parallelism. Only report if we have Serial/Parallel/CMS/G1 events. if (jvmRun.getCollectorFamilies() != null && jvmRun.getCollectorFamilies().size() > 0) { bufferedWriter .write("# Parallel Events: " + jvmRun.getParallelCount() + Constants.LINE_SEPARATOR); bufferedWriter.write("# Inverted Parallelism: " + jvmRun.getInvertedParallelismCount() + Constants.LINE_SEPARATOR); if (jvmRun.getInvertedParallelismCount() > 0) { bufferedWriter.write("Max Inverted Parallelism: " + jvmRun.getWorstInvertedParallelismEvent().getLogEntry() + Constants.LINE_SEPARATOR); } } // NewRatio if (jvmRun.getMaxYoungSpace() > 0 && jvmRun.getMaxOldSpace() > 0) { bufferedWriter.write("NewRatio: " + jvmRun.getNewRatio() + Constants.LINE_SEPARATOR); } // Max heap occupancy. bufferedWriter.write( "Max Heap Occupancy: " + jvmRun.getMaxHeapOccupancy() + "K" + Constants.LINE_SEPARATOR); // Max heap space. bufferedWriter .write("Max Heap Space: " + jvmRun.getMaxHeapSpace() + "K" + Constants.LINE_SEPARATOR); if (jvmRun.getMaxPermSpace() > 0) { // Max perm occupancy. bufferedWriter.write("Max Perm/Metaspace Occupancy: " + jvmRun.getMaxPermOccupancy() + "K" + Constants.LINE_SEPARATOR); // Max perm space. bufferedWriter.write("Max Perm/Metaspace Space: " + jvmRun.getMaxPermSpace() + "K" + Constants.LINE_SEPARATOR); } // GC throughput bufferedWriter.write("GC Throughput: "); if (jvmRun.getGcThroughput() == 100 && jvmRun.getBlockingEventCount() > 0) { // Provide clue it's rounded to 100 bufferedWriter.write("~"); } bufferedWriter.write(jvmRun.getGcThroughput() + "%" + Constants.LINE_SEPARATOR); // GC max pause BigDecimal maxGcPause = JdkMath.convertMillisToSecs(jvmRun.getMaxGcPause()); bufferedWriter.write("GC Max Pause: " + maxGcPause.toString() + " secs" + Constants.LINE_SEPARATOR); // GC total pause time BigDecimal totalGcPause = JdkMath.convertMillisToSecs(jvmRun.getTotalGcPause()); bufferedWriter .write("GC Total Pause: " + totalGcPause.toString() + " secs" + Constants.LINE_SEPARATOR); } if (jvmRun.getStoppedTimeEventCount() > 0) { // Stopped time throughput bufferedWriter.write("Stopped Time Throughput: "); if (jvmRun.getStoppedTimeThroughput() == 100 && jvmRun.getStoppedTimeEventCount() > 0) { // Provide clue it's rounded to 100 bufferedWriter.write("~"); } bufferedWriter.write(jvmRun.getStoppedTimeThroughput() + "%" + Constants.LINE_SEPARATOR); // Max stopped time BigDecimal maxStoppedPause = JdkMath.convertMillisToSecs(jvmRun.getMaxStoppedTime()); bufferedWriter.write("Stopped Time Max Pause: " + maxStoppedPause.toString() + " secs" + Constants.LINE_SEPARATOR); // Total stopped time BigDecimal totalStoppedTime = JdkMath.convertMillisToSecs(jvmRun.getTotalStoppedTime()); bufferedWriter.write( "Stopped Time Total: " + totalStoppedTime.toString() + " secs" + Constants.LINE_SEPARATOR); // Ratio of GC vs. stopped time. 100 means all stopped time due to GC. if (jvmRun.getBlockingEventCount() > 0) { bufferedWriter.write( "GC/Stopped Ratio: " + jvmRun.getGcStoppedRatio() + "%" + Constants.LINE_SEPARATOR); } } // First/last timestamps if (jvmRun.getBlockingEventCount() > 0 || jvmRun.getStoppedTimeEventCount() > 0) { // First event String firstEventDatestamp = JdkUtil.getDateStamp(jvmRun.getFirstEvent().getLogEntry()); if (firstEventDatestamp != null) { bufferedWriter.write("First Datestamp: "); bufferedWriter.write(firstEventDatestamp); bufferedWriter.write(Constants.LINE_SEPARATOR); } bufferedWriter.write("First Timestamp: "); BigDecimal firstEventTimestamp = JdkMath.convertMillisToSecs(jvmRun.getFirstEvent().getTimestamp()); bufferedWriter.write(firstEventTimestamp.toString()); bufferedWriter.write(" secs" + Constants.LINE_SEPARATOR); // Last event String lastEventDatestamp = JdkUtil.getDateStamp(jvmRun.getLastEvent().getLogEntry()); if (lastEventDatestamp != null) { bufferedWriter.write("Last Datestamp: "); bufferedWriter.write(lastEventDatestamp); bufferedWriter.write(Constants.LINE_SEPARATOR); } bufferedWriter.write("Last Timestamp: "); BigDecimal lastEventTimestamp = JdkMath.convertMillisToSecs(jvmRun.getLastEvent().getTimestamp()); bufferedWriter.write(lastEventTimestamp.toString()); bufferedWriter.write(" secs" + Constants.LINE_SEPARATOR); } bufferedWriter.write("========================================" + Constants.LINE_SEPARATOR); // Analysis List<Analysis> analysis = jvmRun.getAnalysis(); if (!analysis.isEmpty()) { // Determine analysis levels List<Analysis> error = new ArrayList<Analysis>(); List<Analysis> warn = new ArrayList<Analysis>(); List<Analysis> info = new ArrayList<Analysis>(); Iterator<Analysis> iterator = analysis.iterator(); while (iterator.hasNext()) { Analysis a = iterator.next(); String level = a.getKey().split("\\.")[0]; if (level.equals("error")) { error.add(a); } else if (level.equals("warn")) { warn.add(a); } else if (level.equals("info")) { info.add(a); } else { throw new IllegalArgumentException("Unknown analysis level: " + level); } } bufferedWriter.write("ANALYSIS:" + Constants.LINE_SEPARATOR); iterator = error.iterator(); boolean printHeader = true; // ERROR while (iterator.hasNext()) { if (printHeader) { bufferedWriter.write("----------------------------------------" + Constants.LINE_SEPARATOR); bufferedWriter.write("error" + Constants.LINE_SEPARATOR); bufferedWriter.write("----------------------------------------" + Constants.LINE_SEPARATOR); } printHeader = false; Analysis a = iterator.next(); bufferedWriter.write("*"); bufferedWriter.write(a.getValue()); bufferedWriter.write(Constants.LINE_SEPARATOR); } // WARN iterator = warn.iterator(); printHeader = true; while (iterator.hasNext()) { if (printHeader) { bufferedWriter.write("----------------------------------------" + Constants.LINE_SEPARATOR); bufferedWriter.write("warn" + Constants.LINE_SEPARATOR); bufferedWriter.write("----------------------------------------" + Constants.LINE_SEPARATOR); } printHeader = false; Analysis a = iterator.next(); bufferedWriter.write("*"); bufferedWriter.write(a.getValue()); bufferedWriter.write(Constants.LINE_SEPARATOR); } // INFO iterator = info.iterator(); printHeader = true; while (iterator.hasNext()) { if (printHeader) { bufferedWriter.write("----------------------------------------" + Constants.LINE_SEPARATOR); bufferedWriter.write("info" + Constants.LINE_SEPARATOR); bufferedWriter.write("----------------------------------------" + Constants.LINE_SEPARATOR); } printHeader = false; Analysis a = iterator.next(); bufferedWriter.write("*"); bufferedWriter.write(a.getValue()); bufferedWriter.write(Constants.LINE_SEPARATOR); } bufferedWriter.write("========================================" + Constants.LINE_SEPARATOR); } // Unidentified log lines List<String> unidentifiedLogLines = jvmRun.getUnidentifiedLogLines(); if (!unidentifiedLogLines.isEmpty()) { bufferedWriter.write( unidentifiedLogLines.size() + " UNIDENTIFIED LOG LINE(S):" + Constants.LINE_SEPARATOR); bufferedWriter.write("----------------------------------------" + Constants.LINE_SEPARATOR); Iterator<String> iterator = unidentifiedLogLines.iterator(); while (iterator.hasNext()) { String unidentifiedLogLine = iterator.next(); bufferedWriter.write(unidentifiedLogLine); bufferedWriter.write(Constants.LINE_SEPARATOR); } bufferedWriter.write("========================================" + Constants.LINE_SEPARATOR); } } catch ( FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // Close streams if (bufferedWriter != null) { try { bufferedWriter.close(); } catch (IOException e) { e.printStackTrace(); } } if (fileWriter != null) { try { fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } } } }
From source file:org.matsim.contrib.drt.analysis.DynModeTripsAnalyser.java
public static void analyseWaitTimes(String fileName, List<DynModeTrip> trips, int binsize_s) { Collections.sort(trips);//from w w w . j ava 2 s .c o m if (trips.size() == 0) return; int startTime = ((int) (trips.get(0).getDepartureTime() / binsize_s)) * binsize_s; int endTime = ((int) (trips.get(trips.size() - 1).getDepartureTime() / binsize_s) + binsize_s) * binsize_s; Map<Double, List<DynModeTrip>> splitTrips = splitTripsIntoBins(trips, startTime, endTime, binsize_s); DecimalFormat format = new DecimalFormat(); format.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US)); format.setMinimumIntegerDigits(1); format.setMaximumFractionDigits(2); format.setGroupingUsed(false); SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm:ss"); BufferedWriter bw = IOUtils.getBufferedWriter(fileName + ".csv"); TimeSeriesCollection dataset = new TimeSeriesCollection(); TimeSeriesCollection datasetrequ = new TimeSeriesCollection(); TimeSeries averageWaitC = new TimeSeries("average"); TimeSeries medianWait = new TimeSeries("median"); TimeSeries p_5Wait = new TimeSeries("5th percentile"); TimeSeries p_95Wait = new TimeSeries("95th percentile"); TimeSeries requests = new TimeSeries("Ride requests"); try { bw.write("timebin;trips;average_wait;min;p_5;p_25;median;p_75;p_95;max"); for (Entry<Double, List<DynModeTrip>> e : splitTrips.entrySet()) { long rides = 0; double averageWait = 0; double min = 0; double p_5 = 0; double p_25 = 0; double median = 0; double p_75 = 0; double p_95 = 0; double max = 0; if (!e.getValue().isEmpty()) { DescriptiveStatistics stats = new DescriptiveStatistics(); for (DynModeTrip t : e.getValue()) { stats.addValue(t.getWaitTime()); } rides = stats.getN(); averageWait = stats.getMean(); min = stats.getMin(); p_5 = stats.getPercentile(5); p_25 = stats.getPercentile(25); median = stats.getPercentile(50); p_75 = stats.getPercentile(75); p_95 = stats.getPercentile(95); max = stats.getMax(); } Minute h = new Minute(sdf2.parse(Time.writeTime(e.getKey()))); medianWait.addOrUpdate(h, Double.valueOf(median)); averageWaitC.addOrUpdate(h, Double.valueOf(averageWait)); p_5Wait.addOrUpdate(h, Double.valueOf(p_5)); p_95Wait.addOrUpdate(h, Double.valueOf(p_95)); requests.addOrUpdate(h, rides * 3600. / binsize_s);// normalised [req/h] bw.newLine(); bw.write(Time.writeTime(e.getKey()) + ";" + rides + ";" + format.format(averageWait) + ";" + format.format(min) + ";" + format.format(p_5) + ";" + format.format(p_25) + ";" + format.format(median) + ";" + format.format(p_75) + ";" + format.format(p_95) + ";" + format.format(max)); } bw.flush(); bw.close(); dataset.addSeries(averageWaitC); dataset.addSeries(medianWait); dataset.addSeries(p_5Wait); dataset.addSeries(p_95Wait); datasetrequ.addSeries(requests); JFreeChart chart = chartProfile(splitTrips.size(), dataset, "Waiting times", "Wait time (s)"); JFreeChart chart2 = chartProfile(splitTrips.size(), datasetrequ, "Ride requests per hour", "Requests per hour (req/h)"); ChartSaveUtils.saveAsPNG(chart, fileName, 1500, 1000); ChartSaveUtils.saveAsPNG(chart2, fileName + "_requests", 1500, 1000); } catch (IOException | ParseException e) { e.printStackTrace(); } }