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:com.cloudera.csd.tools.codahale.AbstractCodahaleFixtureGenerator.java

/**
 * Writes usage message to 'stream'./*from ww  w . ja  va 2s  .com*/
 *
 * @param stream output stream.
 * @throws UnsupportedEncodingException
 */
public static void printUsageMessage(OutputStream stream, Options options) throws UnsupportedEncodingException {
    PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream, "UTF-8")));
    try {
        String header = "Mgmt Metric Schema Generator";
        String footer = "";
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(writer, HelpFormatter.DEFAULT_WIDTH, "schema generator", header, options,
                HelpFormatter.DEFAULT_LEFT_PAD, HelpFormatter.DEFAULT_DESC_PAD, footer, true); // auto-usage: whether to also show
                                                                                                                                                                                             // the command line args on the usage line.
    } finally {
        writer.close();
    }
}

From source file:com.spidasoftware.EclipseFormatter.Formatter.java

/**
 * A two-argument method that will take a fileName string and the contents of 
 * that file (before formatted), and return a backup file.
 *
 * @param fileName  string representing the name of the file.
 * @param before  string containing the contents of that file
 * @return a String that represents the name of the backup file created, null otherwise.
 *
 *///from   w ww  .j a v a2  s .  co m
public static String createBackupFile(String fileName, String before) {
    String nameWithDate = null;
    PrintWriter safety = null;
    try {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("MM_dd_yyyy_h_mm_ss");
        String formattedDate = sdf.format(date);
        nameWithDate = fileName + "_BACKUP_" + formattedDate;
        FileWriter file = new FileWriter(nameWithDate);
        safety = new PrintWriter(file);
        safety.print(before);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (safety != null) {
            safety.close();
        }
    }

    return nameWithDate;
}

From source file:com.quattroresearch.helm.HlConfigEntry.java

public static void handleInputOutputFiles(String ifilename, String ofilename)
        throws IOException, JDOMException {
    BufferedReader br = new BufferedReader(new FileReader(ifilename));
    PrintWriter pw = new PrintWriter(ofilename);
    String helmString;// w  w  w.  j  a  va 2s . c om

    // initialize the output HTML file:
    pw.println("<html>\n<head>\n<meta charset=\"UTF-8\">\n<font style=\"font-size: "
            + defaultFontsizeEntry.value + "pt\">\n</head>\n<body>");

    while ((helmString = br.readLine()) != null) { // read and process all HELM2-Strings from the input file
        processHelmString(helmString, pw);
    }
    br.close();

    pw.println("</body>\n</html>"); // write out the closing HTML sequence
    pw.flush();
    pw.close();
}

From source file:com.erudika.para.rest.RestUtils.java

/**
 * A generic JSON response returning an object. Status code is always {@code 200}.
 * @param response the response to write to
 * @param obj an object//from  w ww .ja va2s .  c  o  m
 */
public static void returnObjectResponse(HttpServletResponse response, Object obj) {
    if (response == null) {
        return;
    }
    PrintWriter out = null;
    try {
        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType(MediaType.APPLICATION_JSON);
        out = response.getWriter();
        ParaObjectUtils.getJsonWriter().writeValue(out, obj);
    } catch (Exception ex) {
        logger.error(null, ex);
    } finally {
        if (out != null) {
            out.close();
        }
    }
}

From source file:at.tuwien.ifs.somtoolbox.data.InputDataWriter.java

public static void writeAsSOMLib(InputData data, String fileName) throws IOException {
    PrintWriter writer = FileUtils.openFileForWriting("Input vector file", fileName, true);
    InputDataWriter.writeHeaderToFile(writer, data.numVectors(), data.dim());
    for (int i = 0; i < data.numVectors(); i++) {
        InputDatum inputDatum = data.getInputDatum(i);
        InputDataWriter.writeInputDatumToFile(writer, inputDatum);
    }//from w  w  w. j  av  a 2  s  .co m

    writer.flush();
    writer.close();
}

From source file:me.ywork.ticket.suite.controller.DingServiceController.java

/**
 * ??//ww w .j a v a 2 s . co m
 */
private static void doSuccessResponse(DingTalkEncryptor dingTalkEncryptor, HttpServletResponse response,
        String encryptStr, String msgSignature, String timeStamp, String nonceStr) {
    try {
        Long longTime = Long.parseLong(timeStamp);
        Map<String, String> jsonMap = dingTalkEncryptor.getEncryptedMap(encryptStr, longTime, nonceStr);

        PrintWriter printWriter = response.getWriter();
        printWriter.print(JSONObject.toJSONString(jsonMap));
        printWriter.close();
        printWriter = null;
    } catch (Exception e) {
        logger.error("doSuccessResponse", e);
    }
}

From source file:com.jaeksoft.searchlib.parser.ExternalParser.java

public final static void doParserContent(Parser parser, File tempDir, final IndexDocument sourceDocument,
        final StreamLimiter streamLimiter, final LanguageEnum lang)
        throws IOException, SearchLibException, TransformerConfigurationException, SAXException {
    PrintWriter configWriter = null;
    ByteArrayOutputStream err = null;
    ByteArrayOutputStream out = null;
    try {/*from  w  ww. jav a2  s. c om*/
        // Prepare the files JSON and XML
        Command command = new Command(sourceDocument, streamLimiter, lang);
        File commandFile = new File(tempDir, FILE_PARSER_COMMAND);
        JsonUtils.jsonToFile(command, commandFile);
        File configFile = new File(tempDir, FILE_PARSER_CONFIG);
        configWriter = new PrintWriter(configFile, FILE_PARSER_ENCODING);
        XmlWriter xmlWriter = new XmlWriter(configWriter, FILE_PARSER_ENCODING);
        parser.writeXmlConfig(xmlWriter);
        xmlWriter.endDocument();
        configWriter.close();

        // Execute
        out = new ByteArrayOutputStream();
        err = new ByteArrayOutputStream();
        String classPath = ExecuteUtils.getClassPath();
        if (!StringUtils.isEmpty(ADDITIONAL_CLASSPATH))
            classPath = StringUtils.fastConcat(classPath, SystemUtils.PATH_SEPARATOR, ADDITIONAL_CLASSPATH);
        int statusCode = ExecuteUtils.command(tempDir, "java", classPath, true, out, err, 3600000L,
                ExternalParser.class.getName());
        if (statusCode != 0)
            throw new SearchLibException(err.toString("UTF-8"));
        File fileParserResults = new File(tempDir, FILE_PARSER_RESULTS);
        if (!fileParserResults.exists())
            return;
        Results results = JsonUtils.getObject(fileParserResults, Results.class);
        if (!StringUtils.isEmpty(results.error)) {
            Logging.warn("External parser error: " + err.toString());
            throw new SearchLibException.ExternalParserException(results.error);
        }
        parser.setExternalResults(results);
    } catch (ExecuteException e) {
        if (err != null)
            Logging.error(err.toString("UTF-8"));
        throw e;
    } finally {
        IOUtils.close(configWriter, err, out);
    }
}

From source file:com.caved_in.commons.utilities.StringUtil.java

public static String getStackStr(Throwable err) {
    if (err == null) {// || err.getCause() == null) {
        return "";
    }// w ww  . j  av  a  2  s  .  com
    StringUtil stackoutstream = new StringUtil();
    PrintWriter stackstream = new PrintWriter(stackoutstream);
    err.printStackTrace(stackstream);
    stackstream.flush();
    stackstream.close();
    return stackoutstream.text.toString();

}

From source file:Gen.java

public static void embedRScripts() throws Exception {
    {/*w  w w  . j a va 2 s  . com*/
        File embedScriptFile = new File(GEN_ROOT_SRC + FILE_SEPARATOR + "bootstrap.R");
        PrintWriter pw = new PrintWriter(new FileWriter(embedScriptFile));
        pw.println(embedScriptBuffer);
        pw.close();
    }

    for (Iterator<?> iter = DirectJNI._rPackageInterfacesHash.keySet().iterator(); iter.hasNext();) {
        String className = (String) iter.next();
        String packageName = className.substring(className.lastIndexOf('.') + 1);
        File packScriptFile = new File(
                GEN_ROOT_SRC + FILE_SEPARATOR + className.replace('.', FILE_SEPARATOR) + ".R");
        PrintWriter pw = new PrintWriter(new FileWriter(packScriptFile));
        pw.println(
                packageEmbedScriptHashMap.get(packageName) != null ? packageEmbedScriptHashMap.get(packageName)
                        : "## No Init Required");
        pw.close();
    }
}

From source file:com.dien.upload.server.UploadServlet.java

/**
 * Writes a response to the client.// w  ww.j  av a 2s. co m
 */
protected static void renderMessage(HttpServletResponse response, String message, String contentType)
        throws IOException {
    response.setContentType(contentType + "; charset=UTF-8");
    response.setCharacterEncoding("UTF-8");
    PrintWriter out = response.getWriter();
    out.print(message);
    out.flush();
    out.close();
}