List of usage examples for java.io BufferedWriter newLine
public void newLine() throws IOException
From source file:fr.mcc.ginco.rest.services.ExportRestService.java
private File writeExportFile(Thesaurus targetThesaurus, boolean alphabetical) { File temp;// w w w .ja v a 2 s.c o m BufferedWriter out = null; try { temp = File.createTempFile("pattern", ".suffix"); temp.deleteOnExit(); out = new BufferedWriter(new FileWriter(temp)); if (alphabetical) { out.write(LabelUtil.getResourceLabel("export-alphabetical").concat(" ")); } else { out.write(LabelUtil.getResourceLabel("export-hierarchical").concat(" ")); } out.write(targetThesaurus.getTitle()); out.newLine(); out.newLine(); out.flush(); List<FormattedLine> result; if (alphabetical) { result = exportService.getAlphabeticalText(targetThesaurus); } else { result = exportService.getHierarchicalText(targetThesaurus); } for (FormattedLine results : result) { for (int i = 0; i < results.getTabs(); i++) { out.write(TABULATION_DELIMITER); } out.write(StringEscapeUtils.unescapeHtml4(results.getText().replace("'", "'")) .replaceAll("<br>", "")); out.newLine(); out.flush(); } out.close(); } catch (IOException e) { throw new BusinessException("Cannot create temp file!", "cannot-create-file", e); } return temp; }
From source file:br.itecbrazil.serviceftpcliente.model.ThreadEnvio.java
private boolean gravarBackup(File arquivo) { logger.info("Gravando backup do arquivo " + arquivo.getName() + ". Thread: " + Thread.currentThread().getName()); String pathDoBackUp = arquivo.getParent().concat(File.separator).concat("backup"); File diretorio = new File(pathDoBackUp); FileReader fr = null;// w ww .ja va 2 s. c o m BufferedReader br = null; FileWriter fw = null; BufferedWriter bw = null; try { if (!diretorio.exists()) { diretorio.mkdir(); } File arquivoBackUp = new File(pathDoBackUp.concat(File.separator).concat(arquivo.getName())); fr = new FileReader(arquivo); br = new BufferedReader(fr); fw = new FileWriter(arquivoBackUp); bw = new BufferedWriter(fw); String linha = br.readLine(); while (linha != null) { bw.write(linha); bw.newLine(); bw.flush(); coteudoFileTransfer.append(linha); linha = br.readLine(); } } catch (FileNotFoundException ex) { loggerExceptionEnvio.info(ex); return false; } catch (IOException ex) { loggerExceptionEnvio.info(ex); return false; } finally { try { if (fr != null) fr.close(); if (br != null) br.close(); } catch (IOException ex) { loggerExceptionEnvio.info(ex); return false; } } return true; }
From source file:matrix.CreateTextMatrix.java
public void textMatrix() throws UnsupportedEncodingException, FileNotFoundException, IOException, ParseException { CosSim cossim = new CosSim(); JSONParser jParser = new JSONParser(); BufferedReader in = new BufferedReader(new InputStreamReader( new FileInputStream("/Users/nSabri/Desktop/tweetMatris/userTweets.json"), "ISO-8859-9")); JSONArray a = (JSONArray) jParser.parse(in); File fout = new File("/Users/nSabri/Desktop/tweetMatris.csv"); FileOutputStream fos = new FileOutputStream(fout); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos)); for (int i = 0; i < 1000; i++) { for (int j = 0; j < 1000; j++) { JSONObject tweet1 = (JSONObject) a.get(i); JSONObject tweet2 = (JSONObject) a.get(j); String tweetText1 = tweet1.get("tweets").toString(); String tweetText2 = tweet2.get("tweets").toString(); double CosSimValue = cossim.Cosine_Similarity_Score(tweetText1, tweetText2); CosSimValue = Double.parseDouble(new DecimalFormat("##.###").format(CosSimValue)); bw.write(Double.toString(CosSimValue) + ", "); }/* w ww . j a v a 2 s. co m*/ bw.newLine(); } bw.close(); }
From source file:com.itemanalysis.psychometrics.irt.estimation.MMLEsimulation.java
public synchronized void runICL(int nrep) { String inputPath = "S:/2014-3pl-simulation/simdata/c3"; String[] commands = new String[nrep]; //create all syntax files for (int r = 0; r < nrep; r++) { String fileName = "c3rep" + (r + 1); //Template without priors // String template = // "output -log_file " + inputPath + "/icl-sim-log.txt \n" + // "set_default_model_dichtomous 3PL \n" + // "options -default_prior_b none\n" + // "options -default_prior_a none\n" + // "options -default_prior_c {beta 5 17 0.0 1.0}\n" + // "options -D 1.0\n" + // "allocate_items_dist 40 -num_latent_dist_points 41 -latent_dist_range {-5.1225 5.1225} \n" + // "read_examinees " + inputPath + "/" + fileName + "-icl.txt 40i1 \n" + // "starting_values_dichotomous\n" + // "EM_steps -max_iter 2000 -crit 0.0001\n" + // "write_item_param " + inputPath + "/icl-output/" + fileName + "-icl-output.txt \n" + // "release_items_dist\n"; //Template with priors String template = "output -log_file " + inputPath + "/icl-sim-log.txt \n" + "set_default_model_dichtomous 3PL \n" + "options -default_prior_a {lognormal 0.13 0.6}\n" + "options -default_prior_b {normal 0 2}\n" + "options -default_prior_c {beta 3.5 4.0 0.0 0.5}\n" + "options -D 1.0\n" + "allocate_items_dist 40 -num_latent_dist_points 41 -latent_dist_range {-5.1225 5.1225} \n" + "read_examinees " + inputPath + "/" + fileName + "-icl.txt 40i1 \n" + "starting_values_dichotomous\n" + "EM_steps -max_iter 2000 -crit 0.0001\n" + "write_item_param " + inputPath + "/icl-output/" + fileName + "-icl-output.txt \n" + "release_items_dist\n"; commands[r] = "icl " + inputPath + "/icl-syntax/" + fileName + "-icl-syntax.txt"; File f = new File(inputPath + "/icl-syntax/" + fileName + "-icl-syntax.txt"); try {//from w ww . ja va 2s .co m f.createNewFile(); BufferedWriter writer = new BufferedWriter(new FileWriter(f)); writer.write(template); writer.close(); } catch (IOException ex) { ex.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } } try { File fBat = new File(inputPath + "/icl-syntax/icl-batch.bat"); fBat.createNewFile(); BufferedWriter writer = new BufferedWriter(new FileWriter(fBat)); for (int r = 0; r < nrep; r++) { writer.write(commands[r]); writer.newLine(); } writer.close(); } catch (IOException ex) { ex.printStackTrace(); } }
From source file:com.seniorproject.semanticweb.services.HadoopService.java
private void modifiedPig() throws IOException { String sReadFileName = servletContext.getRealPath("/WEB-INF/classes/PigSPARQL_v1.0/test3.pig"); File file = new File(servletContext.getRealPath("/WEB-INF/classes/PigSPARQL_v1.0/"), "test4.pig"); String sWriteFileName = file.toString(); String sReplaceText = "indata = LOAD '$inputData' USING pigsparql.rdfLoader.ExNTriplesLoader(' ','expand') as (s,p,o)"; String sReadLine = null;/*from w ww . j ava 2 s . c o m*/ try { // FileReader reads text files in the default encoding. FileReader fileReader = new FileReader(sReadFileName); // Always wrap FileReader in BufferedReader. BufferedReader bufferedReader = new BufferedReader(fileReader); FileWriter fileWriter = new FileWriter(sWriteFileName); // Always wrap FileWriter in BufferedWriter. BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); while ((sReadLine = bufferedReader.readLine()) != null) { System.out.println(sReadLine); if (sReadLine.equals( "indata = LOAD '$inputData' USING pigsparql.rdfLoader.ExNTriplesLoader(' ','expand') ;")) { bufferedWriter.write( "indata = LOAD '$inputData' USING pigsparql.rdfLoader.ExNTriplesLoader(' ','expand') as (s,p,o);"); } else { bufferedWriter.write(sReadLine); } bufferedWriter.newLine(); } // Always close files. bufferedReader.close(); bufferedWriter.close(); } catch (FileNotFoundException ex) { System.out.println("Unable to open file '" + sReadFileName + "'"); } catch (IOException ex) { System.out.println("Error reading file '" + sReadFileName + "'"); // Or we could just do this: // ex.printStackTrace(); } }
From source file:com.orange.mmp.bind.JSONClientBinding.java
/** * Sends the request to WebService and return an object built from * JSON response.// w w w . j av a 2s .c o m * @return A binding object in a JSONObject, JSONArray or String */ public Object getResponse(InputStream postData) throws BindingException { StringWriter responseContent = new StringWriter(); BufferedReader reader = null; BufferedWriter writer = null; //Get response try { this.getHttpConnection().init(this.buildURL(), this.timeout); if (postData != null) this.getHttpConnection().sendData(postData); InputStream httpIn = this.getHttpConnection().getData(); if (httpIn != null) { writer = new BufferedWriter(responseContent); reader = new BufferedReader(new InputStreamReader(httpIn, Constants.DEFAULT_ENCODING)); String line = null; while ((line = reader.readLine()) != null) { writer.write(line); writer.newLine(); writer.flush(); } } else return null; } catch (UnsupportedEncodingException uee) { throw new BindingException("Unsupported encoding from " + this.epr + " : " + uee.getMessage()); } catch (IOException ioe) { throw new BindingException("Failed to get response : " + ioe.getMessage()); } catch (MMPNetException mne) { throw new BindingException("Failed to get response : " + mne.getMessage()); } finally { try { if (reader != null) reader.close(); if (writer != null) writer.close(); this.releaseConnection(); } catch (MMPNetException mne) { //Nop, logs in AOP } catch (IOException ioe) { //Nop, logs in AOP } } //Parse response if (responseContent == null) throw new BindingException("Failed to parse response : empty result"); String jsonString = responseContent.toString(); if (jsonString.length() == 0) throw new BindingException("Failed to parse response : empty result"); try { JSONTokener tokener = new JSONTokener(jsonString); return tokener.nextValue(); } catch (JSONException je) { throw new BindingException("Failed to parse response : " + je.getMessage()); } }
From source file:carolina.pegaLatLong.LatLong.java
private void geraCsv(List<InformacaoGerada> gerados) throws IOException { JFileChooser escolha = new JFileChooser(); escolha.setAcceptAllFileFilterUsed(false); escolha.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int i = escolha.showSaveDialog(null); if (i != 1) { System.err.println(escolha.getSelectedFile().getPath() + "\\teste.txt"); String caminho = escolha.getSelectedFile().getPath(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(caminho + "\\teste.csv"), StandardCharsets.ISO_8859_1)); //FileWriter arquivo = new FileWriter(caminho + "\\teste.csv"); //PrintWriter writer = new PrintWriter(arquivo); writer.write("Endereco;Latitude;Longitude"); writer.newLine(); gerados.stream().forEach((gerado) -> { try { System.err.println(gerado.getEnderecoFormatado() + ";" + gerado.getLatitude() + ";" + gerado.getLongitude() + "\n"); writer.write(gerado.getEnderecoFormatado() + ";" + gerado.getLatitude() + ";" + gerado.getLongitude()); writer.newLine();/*from w w w . ja v a 2 s . c o m*/ } catch (IOException ex) { System.err.println("Erro"); } }); writer.close(); JOptionPane.showMessageDialog(null, "Finalizado!"); } }
From source file:BwaPairedAlignment.java
/** * Code to run in each one of the mappers. This is, the alignment with the corresponding entry data * The entry data has to be written into the local filesystem *///from w w w .j a v a2 s . c o m @Override public Iterator<String> call(Integer arg0, Iterator<Tuple2<String, String>> arg1) throws Exception { // STEP 1: Input fastq reads tmp file creation LOG.info("JMAbuin:: Tmp dir: " + this.tmpDir); String fastqFileName1 = this.tmpDir + this.appId + "-RDD" + arg0 + "_1"; String fastqFileName2 = this.tmpDir + this.appId + "-RDD" + arg0 + "_2"; LOG.info("JMAbuin:: Writing file: " + fastqFileName1); LOG.info("JMAbuin:: Writing file: " + fastqFileName2); File FastqFile1 = new File(fastqFileName1); File FastqFile2 = new File(fastqFileName2); FileOutputStream fos1; FileOutputStream fos2; BufferedWriter bw1; BufferedWriter bw2; ArrayList<String> returnedValues = new ArrayList<String>(); //We write the data contained in this split into the two tmp files try { fos1 = new FileOutputStream(FastqFile1); fos2 = new FileOutputStream(FastqFile2); bw1 = new BufferedWriter(new OutputStreamWriter(fos1)); bw2 = new BufferedWriter(new OutputStreamWriter(fos2)); Tuple2<String, String> newFastqRead; while (arg1.hasNext()) { newFastqRead = arg1.next(); bw1.write(newFastqRead._1.toString()); bw1.newLine(); bw2.write(newFastqRead._2.toString()); bw2.newLine(); } bw1.close(); bw2.close(); arg1 = null; returnedValues = this.runAlignmentProcess(arg0, fastqFileName1, fastqFileName2); // Delete temporary files, as they have now been copied to the // output directory LOG.info("JMAbuin:: Deleting file: " + fastqFileName1); FastqFile1.delete(); LOG.info("JMAbuin:: Deleting file: " + fastqFileName2); FastqFile2.delete(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); LOG.error(e.toString()); } return returnedValues.iterator(); }
From source file:br.bireme.ngrams.NGrams.java
public static void export(NGIndex index, final NGSchema schema, final String outFile, final String outFileEncoding) throws IOException { if (index == null) { throw new NullPointerException("index"); }/*from w ww. j ava 2s .co m*/ if (schema == null) { throw new NullPointerException("schema"); } if (outFile == null) { throw new NullPointerException("outFile"); } if (outFileEncoding == null) { throw new NullPointerException("outFileEncoding"); } final Parameters parameters = schema.getParameters(); final TreeMap<Integer, String> fields = new TreeMap<>(); final IndexReader reader = index.getIndexSearcher().getIndexReader(); final int maxdoc = reader.maxDoc(); //final Bits liveDocs = MultiFields.getLiveDocs(reader); final Bits liveDocs = MultiBits.getLiveDocs(reader); final BufferedWriter writer = Files.newBufferedWriter(Paths.get(outFile), Charset.forName(outFileEncoding), StandardOpenOption.CREATE, StandardOpenOption.WRITE); boolean first = true; for (Map.Entry<Integer, br.bireme.ngrams.Field> entry : parameters.sfields.entrySet()) { fields.put(entry.getKey(), entry.getValue().name + NOT_NORMALIZED_FLD); } for (int docID = 0; docID < maxdoc; docID++) { if ((liveDocs != null) && (!liveDocs.get(docID))) continue; final Document doc = reader.document(docID); if (first) { first = false; } else { writer.newLine(); } writer.append(doc2pipe(doc, fields)); } writer.close(); reader.close(); }
From source file:TalkServerThread.java
public void writeToStream(String string, BufferedWriter stream) { if (DEBUG) {// w w w . j av a 2s .co m System.out.println("TalkServer about to forward data: " + string); } try { stream.write(string); stream.newLine(); stream.flush(); if (DEBUG) { System.out.println("TalkServer forwarded string."); } } catch (IOException e) { System.err.println("TalkServer failed to forward string:"); e.printStackTrace(); return; } catch (NullPointerException e) { System.err.println("TalkServer can't forward string " + "since output stream is null."); return; } }