List of usage examples for java.io BufferedWriter append
public Writer append(CharSequence csq) throws IOException
From source file:edu.rice.cs.bioinfo.programs.phylonet.algos.network.InferMLNetworkFromSequences.java
public List<Tuple<Network, Double>> inferNetwork(String[] gtTaxa, List<char[][]> sequences, Map<String, String> allele2species, RateModel gtrsm, double theta, int maxReticulations, int numSol) { if (_optimalNetworks == null) { _optimalNetworks = new Network[numSol]; _optimalScores = new double[numSol]; Arrays.fill(_optimalScores, Double.NEGATIVE_INFINITY); }/* www. ja va 2 s .c o m*/ List<Tuple<char[], Integer>> distinctSequences = summarizeSquences(sequences); String startingNetwork = _startNetwork.toString(); for (int i = 0; i < _numRuns; i++) { System.out.println("Run #" + i); DirectedGraphToGraphAdapter<String, PhyloEdge<String>> speciesNetwork = makeNetwork(startingNetwork); NetworkNeighbourhoodRandomWalkGenerator<DirectedGraphToGraphAdapter<String, PhyloEdge<String>>, String, PhyloEdge<String>> allNeighboursStrategy = new NetworkNeighbourhoodRandomWalkGenerator<DirectedGraphToGraphAdapter<String, PhyloEdge<String>>, String, PhyloEdge<String>>( _operationWeight, makeNode, makeEdge, _seed); AllNeighboursHillClimberFirstBetter<DirectedGraphToGraphAdapter<String, PhyloEdge<String>>, String, PhyloEdge<String>, Double> searcher = new AllNeighboursHillClimberFirstBetter<DirectedGraphToGraphAdapter<String, PhyloEdge<String>>, String, PhyloEdge<String>, Double>( allNeighboursStrategy); Func1<DirectedGraphToGraphAdapter<String, PhyloEdge<String>>, Double> scorer = getScoreFunction(gtTaxa, allele2species, distinctSequences, gtrsm, theta); Comparator<Double> comparator = getDoubleScoreComparator(); HillClimbResult<DirectedGraphToGraphAdapter<String, PhyloEdge<String>>, Double> result = searcher .search(speciesNetwork, scorer, comparator, _maxExaminations, maxReticulations, _maxFailure, _diameterLimit); // search starts here if (resultFile != null) { try { BufferedWriter bw = new BufferedWriter(new FileWriter(resultFile, true)); bw.append("Run #" + i + "\n"); for (int j = 0; j < _optimalNetworks.length; j++) { bw.append(_optimalScores[j] + ": " + _optimalNetworks[j].toString() + "\n"); } bw.newLine(); bw.close(); } catch (Exception e) { System.err.println(e.getMessage()); e.getStackTrace(); } } } List<Tuple<Network, Double>> resultList = new ArrayList<Tuple<Network, Double>>(); for (int i = 0; i < numSol; i++) { if (_optimalNetworks[i] != null) resultList.add(new Tuple<Network, Double>(_optimalNetworks[i], _optimalScores[i])); } //System.out.println("\n #Networks " + result.ExaminationsCount); return resultList; }
From source file:com.ideateam.plugin.Version.java
public void writeLocaleToFile(String fileName, String msg) { try {/*from w w w.j a v a 2 s .co m*/ String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/UAR2015/" + fileName; File file = new File(path); if (!file.exists()) { File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/UAR2015/"); f.mkdirs(); file.createNewFile(); } BufferedWriter buf = new BufferedWriter(new FileWriter(file, true)); buf.append(msg); buf.newLine(); buf.close(); // callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, "writed to file")); Log.d(TAG, "..callBackPlugin"); activity.sendJavascript("UART.system.Helper.callBackPlugin('ok')"); } catch (IOException e) { Log.d(TAG, e.getMessage()); } }
From source file:ie.pars.nlp.sketchengine.interactions.FreqSKEInteraction.java
/** * Get all the results and dump it into files this method can be changed so * Here the difference is that all the res are written into one * * * @throws UnsupportedEncodingException/*from w w w . j a v a 2 s .c om*/ * @throws IOExceptionsket * @throws Exception */ public void getFrequencyContextSingle() throws UnsupportedEncodingException, IOException, Exception { HttpClient sessionID = super.getSessionID(); BufferedWriter writer;// this.writer; //append to the end of file OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(this.fileOutput), StandardCharsets.UTF_8); writer = new BufferedWriter(outputStreamWriter); if (!writeParsed) { writer.append("{\"results\": [\n"); } int pageNumer = 0; while (true) { JSONObject jsonObjP = super.getHTTP(sessionID, encodeFreqQuery(pageNumer)); if (!writeParsed) { writer.append(jsonObjP.toString(1)); } else { FreqMethodJsonParser fjpm = new FreqMethodJsonParser(jsonObjP.toString()); FrequencyLine fl; while ((fl = fjpm.getNext()) != null) { // just to make sure that the output won't be messed up // I may need to change this to a better solution // at least with the current hardware the writer sis not a bottleneck writer.append(fl.toStringLine()).append("\n"); } // writer.flush(); } boolean hasError = jsonObjP.has("error"); if (hasError) { String message = (String) jsonObjP.get("error"); if ("Empty list".equals(message)) { System.out.println("No result for current query: " + this.query); // retrun null etc break; } else { System.out.println("* NOT SEEN * " + jsonObjP.toString(1)); throw new Exception("not seen " + jsonObjP.toString(1)); } } else { int isLastPage = 0; // int finished = (int) jsonObjP.get("finished"); if (jsonObjP.has("lastpage")) { isLastPage = (int) jsonObjP.get("lastpage"); //System.out.println("** IS Last TO GO " + isLastPage); if (isLastPage == 0) { if (!writeParsed) { writer.append(","); } pageNumer++; } else { //System.out.println("Going to break because last page is not 0"); break; } } } } if (!writeParsed) { writer.append("]" + "}"); // to the end the json file} } writer.flush(); writer.close(); }
From source file:com.pieframework.runtime.utils.azure.CsdefGenerator.java
private List<String> printEndpoints(BufferedWriter out, Role r) { //print Endpoints List<String> epList = null; try {//from w w w. j ava 2s . com AzureKey ssl = (AzureKey) r.getResources().get("sslCert"); AzureEndpoint ap = (AzureEndpoint) r.getResources().get("endpoints"); String certName = ssl.getCertificateName(); out.append("<Endpoints>"); if (ap != null) { epList = new ArrayList<String>(); for (String port : ap.getEndpoints().keySet()) { String protocol = ap.getEndpoints().get(port); String id = protocol + port; out.append("<InputEndpoint name=\"" + id + "\" protocol=\"" + protocol + "\" port=\"" + port + "\" "); if (protocol.equalsIgnoreCase("https")) { if (!StringUtils.empty(certName)) { out.append(" certificate=\"" + certName + "\" "); } else { throw new RuntimeException( "Certificate name is not configured in resource " + ssl.getId()); } } out.append("/>"); //Save the endpoint in the map epList.add(id); } } out.append("</Endpoints>"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return epList; }
From source file:org.balloon_project.overflight.task.indexing.IndexingTask.java
private void dumpIndexedTriples(List<Triple> results) throws IOException { Stopwatch storeTimer = Stopwatch.createStarted(); if (results.size() > 0) { BufferedWriter writer = new BufferedWriter(new FileWriter(file, true)); try {//from www .j a va2 s .co m for (Triple triple : results) { StringBuilder sb = new StringBuilder(); sb.append("<").append(triple.getSubject()).append("> <") .append(triple.getRelEntity().getPredicate()).append("> <").append(triple.getObject()) .append(">.\n"); writer.append(sb.toString()); } } finally { writer.flush(); writer.close(); } } logger.debug(this.endpoint.getEndpointID() + ": Intermediate result persisted (Size = " + results.size() + ") Continue query process" + " (save duration: " + storeTimer.stop().elapsed(TimeUnit.MILLISECONDS) + " ms) predicate " + relEntity.getPredicate()); }
From source file:com.termmed.statistics.Processor.java
private void printExcluyentList(IReportDetail file, HashSet<Long> conceptList, File outputFold) throws IOException { File exclFile = new File(I_Constants.EXCLUYENT_OUTPUT_FOLDER + "/" + file.getFile() + (file.getFile().toLowerCase().endsWith(".csv") ? "" : ".csv")); File completeDetailFile = new File(I_Constants.STATS_OUTPUT_FOLDER + "/" + file.getFile() + (file.getFile().toLowerCase().endsWith(".csv") ? "" : ".csv")); BufferedReader br = FileHelper.getReader(completeDetailFile); BufferedWriter bw = FileHelper.getWriter(exclFile); Integer sctIdIndex = file.getSctIdIndex(); if (sctIdIndex == null) { sctIdIndex = 1;//from ww w . jav a 2s . com } bw.append(br.readLine()); bw.append("\r\n"); String line; String[] spl; while ((line = br.readLine()) != null) { spl = line.split(",", -1); Long cid = Long.parseLong(spl[sctIdIndex]); if (conceptList.contains(cid)) { continue; } bw.append(line); bw.append("\r\n"); conceptList.add(cid); } br.close(); bw.close(); }
From source file:analytics.storage.store2csv.java
private void createHeaders(BufferedWriter writer, String metricName, String element) { try {/*from www. ja v a2s . c o m*/ writer.append(element); writer.append(','); writer.append(metricName); writer.newLine(); // writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // finally { // try { // if (writer != null) // writer.close(); // } catch (IOException ex) { // ex.printStackTrace(); // } // } }
From source file:com.itemanalysis.jmetrik.workspace.JmetrikPreferencesManager.java
private void createLogProperties(String logHome) { //directory should already exist //create log4j properties file if it does not exist String header = "#DO NOT EDIT - JMETRIK LOG PROPERTIES FILE - DO NOT EDIT"; String fullPropertiesName = (logHome + "/" + DEFAULT_LOG_PROPERTY_FILE_V4); String fullLogFileName = (logHome + "/" + DEFAULT_LOG_NAME); String fullScriptLogFileName = (logHome + "/" + DEFAULT_SCRIPT_LOG_NAME); File f = new File(fullPropertiesName); if (!f.exists()) { try {/*from w w w . j a v a2s .c o m*/ createLogHome(logHome); f.createNewFile(); BufferedWriter bw = new BufferedWriter(new FileWriter(f)); bw.append(header); bw.newLine(); bw.append("log4j.logger.jmetrik-logger=ALL, adminAppender"); bw.newLine(); bw.append("log4j.logger.jmetrik-script-logger=INFO, scriptAppender"); bw.newLine(); bw.append("log4j.additivity.jmetrik-logger=false"); bw.newLine(); bw.append("log4j.additivity.jmetrik-script-logger=false"); bw.newLine(); //Main appender processes all levels bw.append("log4j.appender.adminAppender=org.apache.log4j.FileAppender"); bw.newLine(); bw.append("log4j.appender.adminAppender.layout=org.apache.log4j.PatternLayout"); bw.newLine(); bw.append("log4j.appender.adminAppender.File=" + fullLogFileName); bw.newLine(); bw.append("log4j.appender.adminAppender.Append=false"); bw.newLine(); bw.append("log4j.appender.adminAppender.layout.ConversionPattern=[%p] %d{DATE} %n%m%n%n"); bw.newLine(); //Script appender processes scripts only bw.append("log4j.appender.scriptAppender=org.apache.log4j.FileAppender"); bw.newLine(); bw.append("log4j.appender.scriptAppender.layout=org.apache.log4j.PatternLayout"); bw.newLine(); bw.append("log4j.appender.scriptAppender.File=" + fullScriptLogFileName); bw.newLine(); bw.append("log4j.appender.scriptAppender.Append=false"); bw.newLine(); bw.append("log4j.appender.scriptAppender.layout.ConversionPattern=%m%n%n"); bw.newLine(); bw.close(); } catch (IOException ex) { firePropertyChange("error", "", "Error - Log properties file could not be created."); } } }
From source file:de.tudarmstadt.ukp.clarin.webanno.automation.util.AutomationUtil.java
public static void generatePredictDocument(MiraTemplate aTemplate, RepositoryService aRepository, AnnotationService aAnnotationService, AutomationService aAutomationService, UserDao aUserDao) throws IOException, UIMAException, ClassNotFoundException { File miraDir = aAutomationService.getMiraDir(aTemplate.getTrainFeature()); if (!miraDir.exists()) { FileUtils.forceMkdir(miraDir);// ww w .j av a 2 s . c o m } String username = SecurityContextHolder.getContext().getAuthentication().getName(); User user = aUserDao.get(username); AnnotationFeature feature = aTemplate.getTrainFeature(); boolean documentChanged = false; for (SourceDocument document : aRepository.listSourceDocuments(feature.getProject())) { if (!document.isProcessed() && !document.isTrainingDocument()) { documentChanged = true; break; } } if (!documentChanged) { return; } AutomationTypeAdapter adapter = (AutomationTypeAdapter) TypeUtil.getAdapter(aAnnotationService, feature.getLayer()); for (SourceDocument document : aRepository.listSourceDocuments(feature.getProject())) { if (!document.isProcessed() && !document.isTrainingDocument()) { File predFile = new File(miraDir, document.getId() + ".pred.ft"); BufferedWriter predOut = new BufferedWriter(new FileWriter(predFile)); JCas jCas; try { jCas = aRepository.readCorrectionCas(document); } catch (Exception e) { jCas = aRepository.readAnnotationCas(document, user); } for (Sentence sentence : select(jCas, Sentence.class)) { predOut.append(getMiraLine(sentence, null, adapter).toString() + "\n"); } predOut.close(); } } }
From source file:de.tudarmstadt.ukp.clarin.webanno.automation.util.AutomationUtil.java
public static void addTabSepTrainDocument(MiraTemplate aTemplate, RepositoryService aRepository, AutomationService aAutomationService) throws IOException, UIMAException, ClassNotFoundException, AutomationException { File miraDir = aAutomationService.getMiraDir(aTemplate.getTrainFeature()); if (!miraDir.exists()) { FileUtils.forceMkdir(miraDir);/*from w w w . ja v a 2s . com*/ } AutomationStatus status = aAutomationService.getAutomationStatus(aTemplate); boolean documentChanged = false; for (SourceDocument document : aAutomationService .listTabSepDocuments(aTemplate.getTrainFeature().getProject())) { if (!document.isProcessed()) { documentChanged = true; break; } } if (!documentChanged) { return; } for (SourceDocument sourceDocument : aAutomationService .listTabSepDocuments(aTemplate.getTrainFeature().getProject())) { if (sourceDocument.getFeature() != null) { // This is a target layer train document continue; } File trainFile = new File(miraDir, sourceDocument.getId() + sourceDocument.getProject().getId() + ".train"); BufferedWriter trainOut = new BufferedWriter(new FileWriter(trainFile)); File tabSepFile = new File(aRepository.getDocumentFolder(sourceDocument), sourceDocument.getName()); LineIterator it = IOUtils.lineIterator(new FileReader(tabSepFile)); while (it.hasNext()) { String line = it.next(); if (line.trim().equals("")) { trainOut.append("\n"); } else { StringTokenizer st = new StringTokenizer(line, "\t"); if (st.countTokens() != 2) { trainOut.close(); throw new AutomationException("This is not a valid TAB-SEP document"); } trainOut.append(getMiraLineForTabSep(st.nextToken(), st.nextToken())); } } sourceDocument.setProcessed(false); status.setTrainDocs(status.getTrainDocs() - 1); trainOut.close(); } }