List of usage examples for java.io PrintWriter PrintWriter
public PrintWriter(File file) throws FileNotFoundException
From source file:Main.java
public static void writeToFile(Document doc, String file) throws Exception { TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); DOMSource source = new DOMSource(doc); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8")); StreamResult result = new StreamResult(pw); transformer.transform(source, result); }
From source file:edu.cornell.med.icb.goby.reads.ColorSpaceConverter.java
public static void main(final String[] args) throws JSAPException, IOException { final JSAP jsap = new JSAP(); final FlaggedOption sequenceOption = new FlaggedOption("input"); sequenceOption.setRequired(true);//from w ww . j a va 2 s . c o m sequenceOption.setLongFlag("input"); sequenceOption.setShortFlag('i'); sequenceOption.setStringParser(FileStringParser.getParser().setMustBeFile(true).setMustExist(true)); sequenceOption.setHelp("The input file (in Fasta format) to convert"); jsap.registerParameter(sequenceOption); final FlaggedOption outputOption = new FlaggedOption("output"); outputOption.setRequired(false); outputOption.setLongFlag("output"); outputOption.setShortFlag('o'); outputOption.setStringParser(FileStringParser.getParser().setMustBeFile(true)); outputOption.setHelp("The output file to write to (default = stdout)"); jsap.registerParameter(outputOption); final FlaggedOption titleOption = new FlaggedOption("title"); titleOption.setRequired(false); titleOption.setLongFlag("title"); titleOption.setShortFlag('t'); titleOption.setHelp("Title for this conversion"); jsap.registerParameter(titleOption); final Switch verboseOption = new Switch("verbose"); verboseOption.setLongFlag("verbose"); verboseOption.setShortFlag('v'); verboseOption.setHelp("Verbose output"); jsap.registerParameter(verboseOption); final Switch helpOption = new Switch("help"); helpOption.setLongFlag("help"); helpOption.setShortFlag('h'); helpOption.setHelp("Print this message"); jsap.registerParameter(helpOption); jsap.setUsage("Usage: " + ColorSpaceConverter.class.getName() + " " + jsap.getUsage()); final JSAPResult result = jsap.parse(args); if (result.getBoolean("help")) { System.out.println(jsap.getHelp()); System.exit(0); } if (!result.success()) { final Iterator<String> errors = result.getErrorMessageIterator(); while (errors.hasNext()) { System.err.println(errors.next()); } System.err.println(jsap.getUsage()); System.exit(1); } final boolean verbose = result.getBoolean("verbose"); final File sequenceFile = result.getFile("input"); if (verbose) { System.out.println("Reading sequence from: " + sequenceFile); } // extract the title to use for the output header final String title; if (result.contains("title")) { title = result.getString("title"); } else { title = sequenceFile.getName(); } Reader inputReader = null; PrintWriter outputWriter = null; try { if ("gz".equals(FilenameUtils.getExtension(sequenceFile.getName()))) { inputReader = new InputStreamReader(new GZIPInputStream(FileUtils.openInputStream(sequenceFile))); } else { inputReader = new FileReader(sequenceFile); } final FastaParser fastaParser = new FastaParser(inputReader); final File outputFile = result.getFile("output"); final OutputStream outputStream; if (outputFile != null) { outputStream = FileUtils.openOutputStream(outputFile); if (verbose) { System.out.println("Writing sequence : " + outputFile); } } else { outputStream = System.out; } outputWriter = new PrintWriter(outputStream); // write the header portion of the output outputWriter.print("# "); outputWriter.print(new Date()); outputWriter.print(' '); outputWriter.print(ColorSpaceConverter.class.getName()); for (final String arg : args) { outputWriter.print(' '); outputWriter.print(arg); } outputWriter.println(); outputWriter.print("# Cwd: "); outputWriter.println(new File(".").getCanonicalPath()); outputWriter.print("# Title: "); outputWriter.println(title); // now parse the input sequence long sequenceCount = 0; final MutableString descriptionLine = new MutableString(); final MutableString sequence = new MutableString(); final MutableString colorSpaceSequence = new MutableString(); while (fastaParser.hasNext()) { fastaParser.next(descriptionLine, sequence); outputWriter.print('>'); outputWriter.println(descriptionLine); convert(sequence, colorSpaceSequence); CompactToFastaMode.writeSequence(outputWriter, colorSpaceSequence); sequenceCount++; if (verbose && sequenceCount % 10000 == 0) { System.out.println("Converted " + sequenceCount + " entries"); } } if (verbose) { System.out.println("Conversion complete!"); } } finally { IOUtils.closeQuietly(inputReader); IOUtils.closeQuietly(outputWriter); } }
From source file:Main.java
private static String createPKCS11ConfigFile(String pkcs11LibPath) { File f = null;// w w w. j a v a 2 s . c o m PrintWriter writer = null; try { f = File.createTempFile("pkcs11", ".cfg"); f.deleteOnExit(); writer = new PrintWriter(new FileOutputStream(f)); writer.println("name = verinice"); writer.println("description = verinice PKCS#11 configuration"); writer.println("library = " + pkcs11LibPath); writer.close(); } catch (IOException e) { return null; } finally { if (writer != null) writer.close(); } return f.getAbsolutePath(); }
From source file:Main.java
/** * Saves an index (Hashtable) to a file. * //from ww w.j a v a 2s . co m * @param root_ * The file where the index is stored in. * @param index * The indextable. * @exception IOException * If an internal error prevents the file from being written. */ public static void saveIndex(File root_, String name, Hashtable index) throws IOException { File indexfile = new File(root_, name); PrintWriter out = new PrintWriter(new FileWriter(indexfile)); Enumeration keys = index.keys(); String key = null; while (keys.hasMoreElements()) { key = (String) keys.nextElement(); out.println(key); out.println((Long) index.get(key)); } out.close(); }
From source file:Main.java
/** * This method is used to send a XML request file to web server to process the request and return * xml response containing event id./*w ww. j a v a 2s.c o m*/ */ public static String postXMLWithTimeout(String postUrl, String xml, int readTimeout) throws Exception { System.out.println("XMLUtils.postXMLWithTimeout: Connecting to Web Server ......."); InputStream in = null; BufferedReader bufferedReader = null; OutputStream out = null; PrintWriter printWriter = null; StringBuffer responseMessageBuffer = new StringBuffer(""); try { URL url = new URL(postUrl); URLConnection con = url.openConnection(); // Prepare for both input and output con.setDoInput(true); con.setDoOutput(true); // Turn off caching con.setUseCaches(false); con.setRequestProperty("Content-Type", "text/xml"); con.setReadTimeout(readTimeout); out = con.getOutputStream(); // Write the arguments as post data printWriter = new PrintWriter(out); printWriter.println(xml); printWriter.flush(); //Process response and return back to caller function in = con.getInputStream(); bufferedReader = new BufferedReader(new InputStreamReader(in)); String tempStr = null; int tempClearResponseMessageBufferCounter = 0; while ((tempStr = bufferedReader.readLine()) != null) { tempClearResponseMessageBufferCounter++; //clear the buffer for the first time if (tempClearResponseMessageBufferCounter == 1) responseMessageBuffer.setLength(0); responseMessageBuffer.append(tempStr); } } catch (Exception ex) { throw ex; } finally { System.out.println("Calling finally in POSTXML"); try { if (in != null) in.close(); } catch (Exception eex) { System.out.println("COULD NOT Close Input Stream in try"); } try { if (out != null) out.close(); } catch (Exception eex) { System.out.println("COULD NOT Close Output Stream in try"); } } System.out.println("XMLUtils.postXMLWithTimeout: end ......."); return responseMessageBuffer.toString(); }
From source file:fr.inria.atlanmod.instantiator.neoEMF.Launcher.java
public static void main(String[] args) throws GenerationException, IOException { ResourceSetImpl resourceSet = new ResourceSetImpl(); { // initializing the registry resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(EcorePackage.eNS_PREFIX, new EcoreResourceFactoryImpl()); resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap() .put(Resource.Factory.Registry.DEFAULT_EXTENSION, new XMIResourceFactoryImpl()); resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap().put(NeoEMFURI.NEOEMF_HBASE_SCHEME, NeoEMFResourceFactory.eINSTANCE); }/*from w ww .j a v a 2 s . c o m*/ Options options = new Options(); configureOptions(options); CommandLineParser parser = new GnuParser(); try { CommandLine commandLine = parser.parse(options, args); String epackage_class = commandLine.getOptionValue(E_PACKAGE_CLASS); LOGGER.info("Start loading the package"); Class<?> inClazz = Launcher.class.getClassLoader().loadClass(epackage_class); EPackage _package = (EPackage) inClazz.getMethod("init").invoke(null); Resource metamodelResource = new XMIResourceImpl(URI.createFileURI("dummy")); metamodelResource.getContents().add(_package); LOGGER.info("Finish loading the package"); int size = Launcher.DEFAULT_AVERAGE_MODEL_SIZE; if (commandLine.hasOption(SIZE)) { Number number = (Number) commandLine.getParsedOptionValue(SIZE); size = (int) Math.min(Integer.MAX_VALUE, number.longValue()); } float variation = Launcher.DEFAULT_DEVIATION; if (commandLine.hasOption(VARIATION)) { Number number = (Number) commandLine.getParsedOptionValue(VARIATION); if (number.floatValue() < 0.0f || number.floatValue() > 1.0f) { throw new ParseException(MessageFormat.format("Invalid value for option -{0}: {1}", VARIATION, number.floatValue())); } variation = number.floatValue(); } float propVariation = Launcher.DEFAULT_DEVIATION; if (commandLine.hasOption(PROP_VARIATION)) { Number number = (Number) commandLine.getParsedOptionValue(PROP_VARIATION); if (number.floatValue() < 0.0f || number.floatValue() > 1.0f) { throw new ParseException(MessageFormat.format("Invalid value for option -{0}: {1}", PROP_VARIATION, number.floatValue())); } propVariation = number.floatValue(); } long seed = System.currentTimeMillis(); if (commandLine.hasOption(SEED)) { seed = ((Number) commandLine.getParsedOptionValue(SEED)).longValue(); } Range<Integer> range = Range.between(Math.round(size * (1 - variation)), Math.round(size * (1 + variation))); GenericMetamodelConfig config = new GenericMetamodelConfig(metamodelResource, range, seed); GenericMetamodelGenerator modelGen = new GenericMetamodelGenerator(config); if (commandLine.hasOption(OUTPUT_PATH)) { String outDir = commandLine.getOptionValue(OUTPUT_PATH); //java.net.URI intermediateURI = java.net.URI.create(outDir); modelGen.setSamplesPath(outDir); } int numberOfModels = 1; if (commandLine.hasOption(N_MODELS)) { numberOfModels = ((Number) commandLine.getParsedOptionValue(N_MODELS)).intValue(); } int valuesSize = GenericMetamodelConfig.DEFAULT_AVERAGE_VALUES_LENGTH; if (commandLine.hasOption(VALUES_SIZE)) { Number number = (Number) commandLine.getParsedOptionValue(VALUES_SIZE); valuesSize = (int) Math.min(Integer.MAX_VALUE, number.longValue()); } int referencesSize = GenericMetamodelConfig.DEFAULT_AVERAGE_REFERENCES_SIZE; if (commandLine.hasOption(VALUES_SIZE)) { Number number = (Number) commandLine.getParsedOptionValue(DEGREE); referencesSize = (int) Math.min(Integer.MAX_VALUE, number.longValue()); } config.setValuesRange(Math.round(valuesSize * (1 - propVariation)), Math.round(valuesSize * (1 + propVariation))); config.setReferencesRange(Math.round(referencesSize * (1 - propVariation)), Math.round(referencesSize * (1 + propVariation))); config.setPropertiesRange(Math.round(referencesSize * (1 - propVariation)), Math.round(referencesSize * (1 + propVariation))); long start = System.currentTimeMillis(); modelGen.runGeneration(resourceSet, numberOfModels, size, variation); long end = System.currentTimeMillis(); LOGGER.info( MessageFormat.format("Generation finished after {0} s", Long.toString((end - start) / 1000))); if (commandLine.hasOption(DIAGNOSE)) { for (Resource resource : resourceSet.getResources()) { LOGGER.info( MessageFormat.format("Requested validation for resource ''{0}''", resource.getURI())); BasicDiagnostic diagnosticChain = diagnoseResource(resource); if (!isFailed(diagnosticChain)) { LOGGER.info(MessageFormat.format("Result of the diagnosis of resurce ''{0}'' is ''OK''", resource.getURI())); } else { LOGGER.severe(MessageFormat.format("Found ''{0}'' error(s) in the resource ''{1}''", diagnosticChain.getChildren().size(), resource.getURI())); for (Diagnostic diagnostic : diagnosticChain.getChildren()) { LOGGER.fine(diagnostic.getMessage()); } } } LOGGER.info("Validation finished"); } } catch (ParseException e) { System.err.println(e.getLocalizedMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.setOptionComparator(new OptionComarator<Option>()); try { formatter.setWidth(Math.max(Terminal.getTerminal().getTerminalWidth(), 80)); } catch (Throwable t) { LOGGER.warning("Unable to get console information"); } ; formatter.printHelp("java -jar <this-file.jar>", options, true); System.exit(ERROR); } catch (ClassNotFoundException t) { System.err.println("ERROR: Unable to load class" + t.getLocalizedMessage()); StringWriter stringWriter = new StringWriter(); t.printStackTrace(new PrintWriter(stringWriter)); System.err.println(stringWriter.toString()); } catch (Throwable t) { System.err.println("ERROR: " + t.getLocalizedMessage()); StringWriter stringWriter = new StringWriter(); t.printStackTrace(new PrintWriter(stringWriter)); System.err.println(t); LOGGER.severe(stringWriter.toString()); System.exit(ERROR); } }
From source file:com.github.triceo.robozonky.notifications.email.AbstractEmailingListener.java
protected static String stackTraceToString(final Throwable t) { final StringWriter sw = new StringWriter(); final PrintWriter pw = new PrintWriter(sw); t.printStackTrace(pw);/*www .ja va 2 s . c o m*/ return sw.toString(); }
From source file:Utilities.java
/** * Return the stack trace from the passed exception as a string * * @param th The exception to retrieve stack trace for. *//*from www .j ava 2s .com*/ public static String getStackTrace(Throwable th) { if (th == null) { throw new IllegalArgumentException("Throwable == null"); } StringWriter sw = new StringWriter(); try { PrintWriter pw = new PrintWriter(sw); try { th.printStackTrace(pw); return sw.toString(); } finally { pw.close(); } } finally { try { sw.close(); } catch (IOException ex) { } } }
From source file:Main.java
public static String toString(Node element) throws Exception { if (element == null) { return "null"; }// www . j av a2s.co m Source source = new DOMSource(element); StringWriter stringWriter = new StringWriter(); try (PrintWriter printWriter = new PrintWriter(stringWriter)) { Result result = new StreamResult(printWriter); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.transform(source, result); } return stringWriter.toString(); }
From source file:io.uengine.util.StringUtils.java
/** * Properties? key value ? ./* w w w . j a va2s . c o m*/ * * @param properties Properties * @return key value ? */ public static String propertiesToString(Properties properties) { StringWriter writer = new StringWriter(); PrintWriter out = new PrintWriter(writer); Set<Object> keys = properties.keySet(); for (Object key : keys) { out.println(key + "=" + properties.get(key)); } return writer.getBuffer().toString(); }