Example usage for java.io PrintWriter close

List of usage examples for java.io PrintWriter close

Introduction

In this page you can find the example usage for java.io PrintWriter close.

Prototype

public void close() 

Source Link

Document

Closes the stream and releases any system resources associated with it.

Usage

From source file:cz.pecina.bin.bitwriter.Parameters.java

/**
 * Prints usage information./* w  w w . ja v  a 2s . c om*/
 *
 * @param stream print stream for the output
 */
public static void usage(final PrintStream stream) {
    log.fine("Printing usage information");
    final HelpFormatter helpFormatter = new HelpFormatter();
    PrintWriter printWriter = new PrintWriter(stream);
    helpFormatter.printHelp(printWriter, helpFormatter.getWidth(), "bitwriter [options] [--] [input-file]...",
            null, options, helpFormatter.getLeftPadding(), helpFormatter.getDescPadding(),
            "(C) 2015 Tom Pecina <tomas@pecina.cz>, license: GNU/GPL");
    printWriter.close();
}

From source file:org.apache.lens.regression.util.Util.java

public static void writeFile(String fileName, String str) {
    try {/*from   w w w.  j a v  a 2 s.com*/
        PrintWriter out = new PrintWriter(fileName, "UTF-8");
        out.println(str);
        out.close();
    } catch (IOException e) {
        log.info("File Exception : ", e);
    }
}

From source file:de.tudarmstadt.ukp.experiments.argumentation.sequence.feature.coreference.CoreferenceFeatures.java

private static String chainToString(List<CoreferenceLink> chain) {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    for (CoreferenceLink link : chain) {
        pw.printf("-> %s (%s) ", link.getCoveredText(), link.getReferenceType());
    }/*ww w  .j ava2s  . c om*/

    pw.close();
    return sw.toString();
}

From source file:es.csic.iiia.planes.cli.Cli.java

/**
 * Parse the provided list of arguments according to the program's options.
 * //from  w  ww  .ja va2  s .  c o m
 * @param in_args
 *            list of input arguments.
 * @return a configuration object set according to the input options.
 */
private static Configuration parseOptions(String[] in_args) {
    CommandLineParser parser = new PosixParser();
    CommandLine line = null;
    Properties settings = loadDefaultSettings();

    try {
        line = parser.parse(options, in_args);
    } catch (ParseException ex) {
        Logger.getLogger(Cli.class.getName()).log(Level.SEVERE, ex.getLocalizedMessage(), ex);
        showHelp();
    }

    if (line.hasOption('h')) {
        showHelp();
    }

    if (line.hasOption('d')) {
        dumpSettings();
    }

    if (line.hasOption('s')) {
        String fname = line.getOptionValue('s');
        try {
            settings.load(new FileReader(fname));
        } catch (IOException ex) {
            throw new IllegalArgumentException("Unable to load the settings file \"" + fname + "\"");
        }
    }

    // Apply overrides
    settings.setProperty("gui", String.valueOf(line.hasOption('g')));
    settings.setProperty("quiet", String.valueOf(line.hasOption('q')));
    Properties overrides = line.getOptionProperties("o");
    settings.putAll(overrides);

    String[] args = line.getArgs();
    if (args.length < 1) {
        showHelp();
    }
    settings.setProperty("problem", args[0]);

    Configuration c = new Configuration(settings);
    System.out.println(c.toString());
    /**
     * Modified by Guillermo B. Print settings to a result file, titled
     * "results.txt"
     */
    try {
        FileWriter fw = new FileWriter("results.txt", true);
        BufferedWriter bw = new BufferedWriter(fw);
        PrintWriter out = new PrintWriter(bw);
        String[] results = c.toString().split("\n");
        // out.println(results[8]);

        for (String s : results) {
            out.println(s);

        }
        // out.println(results[2]);
        // out.println(results[8]);
        out.close();
    } catch (IOException e) {
    }

    /**
     * Modified by Ebtesam Save settings to a .csv file, titled
     * "resultsCSV.csv"
     */

    try {
        FileWriter writer = new FileWriter("resultsCSV.csv", true);
        FileReader reader = new FileReader("resultsCSV.csv");

        String header = "SAR Strategy,# of Searcher UAVs,# of Survivors,"
                + "# of Survivors rescued,Min.Time needed to rescue Survivors,Mean. Time needed to rescue Survivors,Max. Time needed to rescue Survivors,"
                + "# of Survivors found,Min. Time needed to find Survivors,Mean Time needed to find Survivors,Max. Time needed to find Survivors,"
                + "Running Time of Simulation\n";
        if (reader.read() == -1) {
            writer.append(header);
            writer.append("\n");
        }
        reader.close();
        String[] results = c.toString().split("\n");
        writer.append(results[2].substring(10));
        writer.append(",");
        writer.append(results[20].substring(11));
        writer.append(",");
        writer.append(results[30].substring(18));
        writer.write(",");
        writer.close();
    } catch (IOException e) {
    }

    if (line.hasOption('t')) {
        System.exit(0);
    }
    return c;
}

From source file:eu.trentorise.opendata.jackan.test.ckan.CkanTestReporter.java

public static void saveToDirectory(File outputDirectory, String indexContent, RunSuite runSuite) {

    outputDirectory.mkdirs();/*from  ww  w.  ja v  a 2 s  .  co m*/

    PrintWriter outIndex;
    try {
        outIndex = new PrintWriter(outputDirectory + "/index.html");
        outIndex.write(indexContent);
        outIndex.close();

        for (TestResult result : runSuite.getResults()) {
            PrintWriter outResult;
            String resultHtml = renderTestResult(result);
            outResult = new PrintWriter(outputDirectory + "/" + TEST_RESULT_PREFIX + result.getId() + ".html");
            outResult.write(resultHtml);
            outResult.close();
        }

        logger.log(Level.INFO, "Report is now available at {0}{1}index.html",
                new Object[] { outputDirectory.getAbsolutePath(), File.separator });
    } catch (FileNotFoundException ex) {
        logger.log(Level.SEVERE, null, ex);
    }
}

From source file:gda.util.persistence.LocalParameters.java

/**
 * @param configDir// w  w w  .ja  va  2s  . co  m
 * @param configName
 * @param createIfMissing
 * @param createAlways true if existing config in the cache is to be thrown away - re-reads the underlying file
 * @return XMLConfiguration
 * @throws ConfigurationException
 * @throws IOException
 */
public synchronized static XMLConfiguration getXMLConfiguration(String configDir, String configName,
        Boolean createIfMissing, boolean createAlways) throws ConfigurationException, IOException {
    // Instantiate the Configuration if it has not been instantiated
    if (configDir == null || configDir.isEmpty())
        throw new IllegalArgumentException("configDir is null or empty");
    if (!configDir.endsWith(File.separator))
        configDir += File.separator;
    final String fullName = getFullName(configDir, configName);
    if (createAlways && configList.containsKey(fullName)) {
        configList.remove(fullName);
    }
    if (configList.containsKey(fullName) == false) {
        XMLConfiguration config;

        // Try to open the file
        try {
            config = loadConfigurationFromFile(fullName);
        } catch (ConfigurationException e)
        // catch (NoClassDefFoundError e)
        {
            // Assume the error occured because the file does not exist

            // Throw exception if createIfMissing is false
            if (createIfMissing == false) {
                logger.error("Could not load " + configDir + configName + ".xml which will not be created");
                throw new ConfigurationException(e);
            }

            // else try to make it...
            try {
                File dir = new File(configDir);
                if (!dir.exists())
                    if (!dir.mkdirs()) {
                        throw new FileNotFoundException("Couldn't create directory: " + dir);
                    }
                File file = new File(fullName);
                PrintWriter out = new PrintWriter(new FileWriter(file));
                out.println("<?xml version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"no\"?>");
                out.println("<" + configName + ">");
                out.println("</" + configName + ">");
                out.close();
            } catch (IOException ee) {
                logger.error("Failed trying to create non-existent file " + fullName);
                throw new IOException(ee);
            }

            // ... and read it again
            try {
                config = loadConfigurationFromFile(fullName);
            } catch (ConfigurationException ee) {
                logger.error("Failed trying to read newly-created file " + fullName);
                throw new ConfigurationException(e);
            }

            logger.debug("Created configuration file: " + fullName);

        } // endif - create a missing file
        config.setReloadingStrategy(new FileChangedReloadingStrategy());
        configList.put(fullName, config);
        logger.debug("Loaded the configuration file: " + fullName);

    } // endif - instantiate a new configuration

    // return the configuration object
    return configList.get(fullName);
}

From source file:Main.java

public static String getStackTrace(Exception e) {
    if (e == null) {
        return "";
    }//from www  . j a  va 2s  .  co m
    StringWriter sw = null;
    PrintWriter pw = null;
    try {
        sw = new StringWriter();
        pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        pw.flush();
        sw.flush();
    } finally {
        if (sw != null) {
            try {
                sw.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        if (pw != null) {
            pw.close();
        }
    }
    return sw.toString();
}

From source file:Main.java

public static String getStackTrace(@Nullable Throwable e) {
    if (e == null) {
        return "";
    }// w  w w.ja  v  a  2s  .c  om
    StringWriter sw = null;
    PrintWriter pw = null;
    try {
        sw = new StringWriter();
        pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        pw.flush();
        sw.flush();
    } finally {
        if (sw != null) {
            try {
                sw.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        if (pw != null) {
            pw.close();
        }
    }
    return sw.toString();
}

From source file:eu.pawelsz.apache.beam.coders.TupleCoderGenerator.java

private static void createTupleClasses(File root) throws FileNotFoundException {
    File dir = getPackage(root, PACKAGE);

    PrintWriter writer = null;
    for (int i = FIRST; i <= LAST; i++) {
        //    for (int i = 4; i <= 4; i++) {
        File tupleFile = new File(dir, "Tuple" + i + "Coder.java");
        writer = new PrintWriter(tupleFile);
        writeTupleCoderClass(writer, i);
        writer.flush();//w  w w  .j  av  a 2 s . c  o m
        writer.close();
    }

    File f = new File(dir, "RegisterTupleCoders.java");
    writer = new PrintWriter(f);
    writeRegistration(writer);
    writer.flush();
    writer.close();
}

From source file:bide.simulation.Simulation.java

private static void generateSimDataFile(String simFile, GelSetting g, int noOfSpot) {
    try {/*from w  ww.  ja v a2 s .  c  o  m*/

        PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(simFile)));
        out.println(g.createLabel());
        for (int j = 0; j < noOfSpot; j++) {
            out.println(j + "\t" + GelSetting.printGel(g.generateSpot()));
        }
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

}