List of usage examples for java.io BufferedWriter BufferedWriter
public BufferedWriter(Writer out)
From source file:com.textocat.textokit.commons.wfstore.DefaultWordformStorePrinter.java
private void run() throws Exception { // deserialize DefaultWordformStore<?> ws = (DefaultWordformStore<?>) deserialize( toBufferedInputStream(openInputStream(serFile))); // print/*w ww. j a va 2s .c o m*/ PrintWriter out; boolean closeOut; if (outFile == null) { out = new PrintWriter(System.out, true); closeOut = false; } else { OutputStream os = openOutputStream(outFile); out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(os, "utf-8")), true); closeOut = true; } try { for (Map.Entry<String, ?> e : ws.strKeyMap.entrySet()) { out.print(escapeTabs(e.getKey())); out.print('\t'); out.print(e.getValue()); out.println(); } } finally { if (closeOut) closeQuietly(out); } }
From source file:edu.gmu.isa681.ctn.EncodedChannel.java
public EncodedChannel(String name, InputStream in, int inboundCapacity, OutputStream out, int outboundCapacity) throws UnsupportedEncodingException { this.name = name; this.sin = new Scanner(new BufferedReader(new InputStreamReader(in, "UTF-8"))); this.sout = new BufferedWriter(new OutputStreamWriter(out, "UTF-8")); startHandlers(inboundCapacity, outboundCapacity); }
From source file:info.novatec.testit.livingdoc.report.FileReportGenerator.java
@Override public void closeReport(Report report) throws IOException { Writer out = null;//from w w w. jav a 2s . co m try { File reportFile = new File(reportsDirectory, outputNameOf(report)); reportFile.getParentFile().mkdirs(); out = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(reportFile.getAbsolutePath()), "UTF-8")); report.printTo(out); out.flush(); } finally { IOUtils.closeQuietly(out); } }
From source file:it.iit.genomics.cru.bridges.liftover.ws.LiftOverRun.java
public static Mapping runLiftOver(String genome, String fromAssembly, String toAssembly, String chromosome, int start, int end) { String liftOverCommand = RESOURCE_BUNDLE.getString("liftOverCommand"); String liftOverPath = RESOURCE_BUNDLE.getString("liftOverPath"); String mapChainDir = RESOURCE_BUNDLE.getString("mapChainDir"); String tmpDir = RESOURCE_BUNDLE.getString("tmpDir"); Mapping mapping = null;/*www .j a v a2s . com*/ Runtime r = Runtime.getRuntime(); String rootFilename = String.format("%s", RandomStringUtils.randomAlphanumeric(8)); String inputFilename = rootFilename + "-" + fromAssembly + ".bed"; String outputFilename = rootFilename + "-" + toAssembly + ".bed"; String unmappedFilename = rootFilename + "-" + "unmapped.bed"; String mapChain = fromAssembly.toLowerCase() + "To" + toAssembly.toUpperCase().charAt(0) + toAssembly.toLowerCase().substring(1) + ".over.chain.gz"; try { File tmpDirFile = new File(tmpDir); // if the directory does not exist, create it if (false == tmpDirFile.exists()) { System.out.println("creating directory: " + tmpDir); boolean result = tmpDirFile.mkdir(); if (result) { System.out.println("DIR created"); } } // Write input bed file File inputFile = new File(tmpDir + inputFilename); // if file doesnt exists, then create it if (!inputFile.exists()) { inputFile.createNewFile(); } FileWriter fw = new FileWriter(inputFile.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); bw.write(chromosome + "\t" + start + "\t" + end + "\n"); bw.close(); String commandArgs = String.format("%s %s %s %s %s", liftOverPath + "/" + liftOverCommand, tmpDir + inputFilename, mapChainDir + mapChain, tmpDir + outputFilename, tmpDir + unmappedFilename); System.out.println(commandArgs); Process p = r.exec(commandArgs); p.waitFor(); BufferedReader b = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = ""; while ((line = b.readLine()) != null) { System.out.println(line); } b.close(); b = new BufferedReader(new FileReader(tmpDir + outputFilename)); while ((line = b.readLine()) != null) { String[] cells = line.split("\t"); String newChromosome = cells[0]; int newStart = Integer.parseInt(cells[1]); int newEnd = Integer.parseInt(cells[2]); mapping = new Mapping(genome, toAssembly, newChromosome, newStart, newEnd); } b.close(); // delete File delete = new File(tmpDir + inputFilename); delete.delete(); delete = new File(tmpDir + outputFilename); delete.delete(); delete = new File(tmpDir + unmappedFilename); delete.delete(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } return mapping; }
From source file:com.mebigfatguy.polycasso.JavaSaver.java
/** * saves the polygon data as a java file that opens a JFrame and draws the polygons * //from w w w . j av a 2 s . c o m * @param fileName the name of the file to write to * @param imageSize the dimension of the image * @param data the polygons to draw */ @Override public void save(String fileName, Dimension imageSize, PolygonData[] data) throws IOException { int sep = fileName.lastIndexOf(File.separator); String className; if (sep >= 0) { className = fileName.substring(sep + 1); } else { className = fileName; } if (className.endsWith(EXTENSION)) { className = className.substring(0, className.length() - EXTENSION.length()); } try (PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(fileName))); InputStream templateStream = getClass() .getResourceAsStream("/com/mebigfatguy/polycasso/JavaSaver.template")) { String template = IOUtils.toString(templateStream); String polygonData = getPolygonData(data); String colorData = getColorData(data); String transparencyData = getTransparencyData(data); /* All the curly braces confuses MessageFormat, so just do it manually */ template = template.replaceAll("\\{0\\}", className); template = template.replaceAll("\\{1\\}", String.valueOf(imageSize.width)); template = template.replaceAll("\\{2\\}", String.valueOf(imageSize.height)); template = template.replaceAll("\\{3\\}", polygonData); template = template.replaceAll("\\{4\\}", colorData); template = template.replaceAll("\\{5\\}", transparencyData); pw.println(template); } catch (IOException ioe) { } }
From source file:fr.univ_tours.li.mdjedaini.ideb.io.GraphWriter.java
/** * //from www . j a v a2s. co m * @param arg_g * @param arg_fileName */ public void writeGraph(Graph<EAB_Vertex, EAB_Edge> arg_g, String arg_fileName) { GraphMLWriter<EAB_Vertex, EAB_Edge> graphWriter = new GraphMLWriter<>(); // set the transformers Transformer<EAB_Vertex, String> vertexID = new Transformer<EAB_Vertex, String>() { public String transform(EAB_Vertex arg_c) { return arg_c.c.cellId.toString(); } }; Transformer<EAB_Vertex, String> vertexLabel = new Transformer<EAB_Vertex, String>() { public String transform(EAB_Vertex cell) { return cell.c.cellId.toString(); //return cell.c.getMondrianCell().getCoordinateList(); } }; Transformer<EAB_Edge, Paint> edgePaint = new Transformer<EAB_Edge, Paint>() { public Paint transform(EAB_Edge edge) { return Color.BLACK; } }; try { // this is for creating directory structure if it does not exist File file = new File(arg_fileName); file.getParentFile().mkdirs(); FileWriter writer = new FileWriter(file); graphWriter.setVertexIDs(vertexID); graphWriter.setVertexDescriptions(vertexLabel); //graphWriter.setvsetVertexIDs(vertexID); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(arg_fileName))); graphWriter.save(arg_g, out); } catch (Exception arg_e) { } }
From source file:ivory.core.tokenize.Tokenizer.java
@SuppressWarnings("static-access") public static void main(String[] args) { Options options = new Options(); options.addOption(OptionBuilder.withArgName("full path to model file or directory").hasArg() .withDescription("model file").create("model")); options.addOption(OptionBuilder.withArgName("full path to input file").hasArg() .withDescription("input file").isRequired().create("input")); options.addOption(OptionBuilder.withArgName("full path to output file").hasArg() .withDescription("output file").isRequired().create("output")); options.addOption(OptionBuilder.withArgName("en | zh | de | fr | ar | tr | es").hasArg() .withDescription("2-character language code").isRequired().create("lang")); options.addOption(OptionBuilder.withArgName("path to stopwords list").hasArg() .withDescription("one stopword per line").create("stopword")); options.addOption(OptionBuilder.withArgName("path to stemmed stopwords list").hasArg() .withDescription("one stemmed stopword per line").create("stemmed_stopword")); options.addOption(OptionBuilder.withArgName("true|false").hasArg().withDescription("turn on/off stemming") .create("stem")); options.addOption(OptionBuilder.withDescription("Hadoop option to load external jars") .withArgName("jar packages").hasArg().create("libjars")); CommandLine cmdline;// w w w . j a v a 2 s .co m CommandLineParser parser = new GnuParser(); try { String stopwordList = null, stemmedStopwordList = null, modelFile = null; boolean isStem = true; cmdline = parser.parse(options, args); if (cmdline.hasOption("stopword")) { stopwordList = cmdline.getOptionValue("stopword"); } if (cmdline.hasOption("stemmed_stopword")) { stemmedStopwordList = cmdline.getOptionValue("stemmed_stopword"); } if (cmdline.hasOption("stem")) { isStem = Boolean.parseBoolean(cmdline.getOptionValue("stem")); } if (cmdline.hasOption("model")) { modelFile = cmdline.getOptionValue("model"); } ivory.core.tokenize.Tokenizer tokenizer = TokenizerFactory.createTokenizer( cmdline.getOptionValue("lang"), modelFile, isStem, stopwordList, stemmedStopwordList, null); BufferedWriter out = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(cmdline.getOptionValue("output")), "UTF8")); BufferedReader in = new BufferedReader( new InputStreamReader(new FileInputStream(cmdline.getOptionValue("input")), "UTF8")); String line = null; while ((line = in.readLine()) != null) { String[] tokens = tokenizer.processContent(line); String s = ""; for (String token : tokens) { s += token + " "; } out.write(s.trim() + "\n"); } in.close(); out.close(); } catch (Exception exp) { System.out.println(exp); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("Tokenizer", options); System.exit(-1); } }
From source file:hu.bme.mit.trainbenchmark.generator.rdf.RDFGenerator.java
@Override public void initModel() throws IOException { // source file (DDL operations) final String srcFilePath = generatorConfig.getWorkspacePath() + "/hu.bme.mit.trainbenchmark.rdf/src/main/resources/metamodel/header.ttl"; final File srcFile = new File(srcFilePath); // destination file final String destFilePath = generatorConfig.getModelPathNameWithoutExtension() + ".ttl"; final File destFile = new File(destFilePath); // this overwrites the destination file if it exists FileUtils.copyFile(srcFile, destFile); file = new BufferedWriter(new FileWriter(destFile, true)); }
From source file:com.commonsware.cwac.locpoll.demo.LocationReceiver.java
@Override public void onReceive(Context context, Intent intent) { mContext = context;/*from w w w . j av a 2 s . c o m*/ File log = new File(Environment.getExternalStorageDirectory(), "LocationLog.txt"); try { BufferedWriter out = new BufferedWriter(new FileWriter(log.getAbsolutePath(), log.exists())); out.write(new Date().toString()); out.write(" : "); Bundle b = intent.getExtras(); loc = (Location) b.get(LocationPoller.EXTRA_LOCATION); String msg; if (loc == null) { loc = (Location) b.get(LocationPoller.EXTRA_LASTKNOWN); if (loc == null) { msg = intent.getStringExtra(LocationPoller.EXTRA_ERROR); } else { msg = "TIMEOUT, lastKnown=" + loc.toString(); } } else { msg = loc.toString(); Log.d("Location Poller", msg); TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); if ((tm.getNetworkType() == TelephonyManager.NETWORK_TYPE_HSDPA)) { Log.d("Type", "3g");// for 3g HSDPA networktype will be return as // per testing(real) in device with 3g enable data // and speed will also matters to decide 3g network type type = 2; } else if ((tm.getNetworkType() == TelephonyManager.NETWORK_TYPE_HSPAP)) { Log.d("Type", "4g"); // /No specification for the 4g but from wiki // i found(HSPAP used in 4g) // http://goo.gl/bhtVT type = 3; } else if ((tm.getNetworkType() == TelephonyManager.NETWORK_TYPE_GPRS)) { Log.d("Type", "GPRS"); type = 1; } else if ((tm.getNetworkType() == TelephonyManager.NETWORK_TYPE_EDGE)) { Log.d("Type", "EDGE 2g"); type = 0; } /* Update the listener, and start it */ MyListener = new MyPhoneStateListener(); Tel = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE); Tel.listen(MyListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS); } if (msg == null) { msg = "Invalid broadcast received!"; } out.write(msg); out.write("\n"); out.close(); } catch (IOException e) { Log.e(getClass().getName(), "Exception appending to log file", e); } }
From source file:edu.indiana.d2i.htrc.util.VectorInspection.java
@Override public int run(String[] args) throws Exception { String input = args[0];//from w w w. j a v a 2 s . co m String output = args[1]; int numVector = 0; Set<Integer> dimLst = new HashSet<Integer>(); Configuration conf = getConf(); FileSystem fs = FileSystem.get(conf); FileStatus[] status = fs.listStatus(new Path(input), Utilities.HIDDEN_FILE_FILTER); Text key = new Text(); VectorWritable value = new VectorWritable(); BufferedWriter writer = new BufferedWriter(new FileWriter(output)); for (int i = 0; i < status.length; i++) { SequenceFile.Reader seqReader = new SequenceFile.Reader(fs, status[i].getPath(), conf); while (seqReader.next(key, value)) { numVector++; dimLst.add(value.get().size()); writer.write(value.toString() + "\n"); } } logger.info("#vector: " + numVector); logger.info("number of different dimensions: " + dimLst.size()); StringBuilder builder = new StringBuilder(); for (Integer dim : dimLst) builder.append(dim + " "); logger.info("" + builder.toString()); writer.close(); return 0; }