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:marytts.util.io.FileUtils.java

public static void writeTextFile(Vector<String> textInRows, String textFile) {
    PrintWriter out = null;
    try {// w w  w.j  a  v a2s.  c  o m
        out = new PrintWriter(new FileWriter(textFile));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    if (out != null) {
        for (int i = 0; i < textInRows.size(); i++)
            out.println(textInRows.get(i));

        out.close();
    } else
        System.out.println("Error! Cannot create file: " + textFile);
}

From source file:it.greenvulcano.util.txt.TextUtils.java

/**
 * Writes a text String into a file/* w ww  .j a  v a  2  s .c  o  m*/
 * 
 * @param contentString
 *        The String to be written into the file
 * @param filename
 *        The name of the file
 * @param append
 *        If true the data are appended to existent file
 * @throws IOException
 */
public static void writeFile(String contentString, String filename, boolean append) throws IOException {
    PrintWriter out = null;
    try {
        filename = adjustPath(filename);
        out = new PrintWriter(new FileWriter(filename, append));
        out.print(contentString);
        out.flush();
    } finally {
        if (out != null) {
            out.close();
        }
    }
}

From source file:com.websqrd.catbot.setting.CatbotSettings.java

public static void saveIncInfo(String site, String category, String incInfo) {
    try {/*w  w w . j  av  a2s . co  m*/
        File f = new File(getSiteKey(site, category + "_" + incInfoFilename));
        PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(f, false)));
        writer.println(incInfo);
        writer.close();
        logger.debug("Save {} / {}  pk >> {} ", new Object[] { site, category, incInfo });
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
}

From source file:it.greenvulcano.util.txt.TextUtils.java

/**
 * Writes a text String into a file// w w w  . j a  v  a  2 s .  c  o  m
 * 
 * @param contentString
 *        The StringBuffer to be written into the file
 * @param filename
 *        The name of the file
 * @param append
 *        If true the data are appended to existent file
 * @throws IOException
 */
@SuppressWarnings("deprecation")
public static void writeFile(StringBuffer contentString, String filename, boolean append) throws IOException {
    PrintWriter out = null;
    try {
        filename = adjustPath(filename);
        out = new PrintWriter(new FileWriter(filename, append));
        IOUtils.write(contentString, out);
        out.flush();
    } finally {
        if (out != null) {
            out.close();
        }
    }
}

From source file:SSLSimpleServer.java

public void run() {
    try {//from   w ww  .ja  v  a  2  s. c om
        BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
        PrintWriter pw = new PrintWriter(sock.getOutputStream());

        String data = br.readLine();
        pw.println(data);
        pw.close();
        sock.close();
    } catch (IOException ioe) {
        // Client disconnected
    }
}

From source file:org.esigate.servlet.impl.ResponseSenderTest.java

public void testSendResponseAlreadySent() throws Exception {
    MockHttpServletResponse httpServletResponse = new MockHttpServletResponse();
    PrintWriter writer = httpServletResponse.getWriter();
    writer.write("Test");
    writer.close();
    CloseableHttpResponse httpClientResponse = BasicCloseableHttpResponse
            .adapt(new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK")));
    httpClientResponse.setEntity(new StringEntity("Abcdefg"));
    renderer.sendResponse(httpClientResponse, null, httpServletResponse);
}

From source file:de.fu_berlin.inf.dpp.netbeans.feedback.FileSubmitter.java

/**
 * Tries to upload the given file to the given HTTP server (via POST
 * method).//from w  w  w  . j a v a2  s. c  o  m
 * 
 * @param file
 *            the file to upload
 * @param url
 *            the URL of the server, that is supposed to handle the file
 * @param monitor
 *            a monitor to report progress to
 * @throws IOException
 *             if an I/O error occurs
 * 
 */

public static void uploadFile(final File file, final String url, IProgressMonitor monitor) throws IOException {

    final String CRLF = "\r\n";
    final String doubleDash = "--";
    final String boundary = generateBoundary();

    HttpURLConnection connection = null;
    OutputStream urlConnectionOut = null;
    FileInputStream fileIn = null;

    if (monitor == null)
        monitor = new NullProgressMonitor();

    int contentLength = (int) file.length();

    if (contentLength == 0) {
        log.warn("file size of file " + file.getAbsolutePath() + " is 0 or the file does not exist");
        return;
    }

    monitor.beginTask("Uploading file " + file.getName(), contentLength);

    try {
        URL connectionURL = new URL(url);

        if (!"http".equals(connectionURL.getProtocol()))
            throw new IOException("only HTTP protocol is supported");

        connection = (HttpURLConnection) connectionURL.openConnection();
        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setReadTimeout(TIMEOUT);
        connection.setConnectTimeout(TIMEOUT);

        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

        String contentDispositionLine = "Content-Disposition: form-data; name=\"" + file.getName()
                + "\"; filename=\"" + file.getName() + "\"" + CRLF;

        String contentTypeLine = "Content-Type: application/octet-stream; charset=ISO-8859-1" + CRLF;

        String contentTransferEncoding = "Content-Transfer-Encoding: binary" + CRLF;

        contentLength += 2 * boundary.length() + contentDispositionLine.length() + contentTypeLine.length()
                + contentTransferEncoding.length() + 4 * CRLF.length() + 3 * doubleDash.length();

        connection.setFixedLengthStreamingMode(contentLength);

        connection.connect();

        urlConnectionOut = connection.getOutputStream();

        PrintWriter writer = new PrintWriter(new OutputStreamWriter(urlConnectionOut, "US-ASCII"), true);

        writer.append(doubleDash).append(boundary).append(CRLF);
        writer.append(contentDispositionLine);
        writer.append(contentTypeLine);
        writer.append(contentTransferEncoding);
        writer.append(CRLF);
        writer.flush();

        fileIn = new FileInputStream(file);
        byte[] buffer = new byte[8192];

        for (int read = 0; (read = fileIn.read(buffer)) > 0;) {
            if (monitor.isCanceled())
                return;

            urlConnectionOut.write(buffer, 0, read);
            monitor.worked(read);
        }

        urlConnectionOut.flush();

        writer.append(CRLF);
        writer.append(doubleDash).append(boundary).append(doubleDash).append(CRLF);
        writer.close();

        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            log.debug("uploaded file " + file.getAbsolutePath() + " to " + connectionURL.getHost());
            return;
        }

        throw new IOException("failed to upload file " + file.getAbsolutePath() + connectionURL.getHost() + " ["
                + connection.getResponseMessage() + "]");
    } finally {
        IOUtils.closeQuietly(fileIn);
        IOUtils.closeQuietly(urlConnectionOut);

        if (connection != null)
            connection.disconnect();

        monitor.done();
    }
}

From source file:AddCookieServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String data = request.getParameter("data");
    Cookie cookie = new Cookie("MyCookie", data);
    response.addCookie(cookie);//from w w w . j  ava  2s  .  c o  m
    response.setContentType("text/html");
    PrintWriter pw = response.getWriter();
    pw.println("<B>MyCookie has been set to");
    pw.println(data);
    pw.close();
}

From source file:com.teamexception.reseravationmaven.controller.VehicleTypeController.java

@RequestMapping(value = "allVehicleTypes", method = RequestMethod.GET)
public void getAllVehilceTypes(HttpServletResponse resp)
        throws ClassNotFoundException, SQLException, IOException {
    ArrayList<VehicleType> types = typeDAO.getAllVehilcesTypes();
    String txt = "<select id=\"type\" class=\"form-control\" name=\"vehicleType\">";
    for (VehicleType type : types) {
        txt += "<option>" + type.getVehicleName() + "</option>";
    }/*w ww .j a v  a  2s  .  c o m*/
    txt += "</select>";
    txt += "<a href=\"addNewVehicleType.jsp\">Add New Vehicle Type</a>";
    PrintWriter out = resp.getWriter();
    out.print(txt);
    out.close();
}

From source file:org.jamwiki.servlets.StylesheetServlet.java

/**
 *
 *//*from w w  w .  j a v a2  s. c om*/
public ModelAndView handleJAMWikiRequest(HttpServletRequest request, HttpServletResponse response,
        ModelAndView next, WikiPageInfo pageInfo) throws Exception {
    String virtualWiki = pageInfo.getVirtualWikiName();
    String stylesheet = ServletUtil.cachedContent(request.getContextPath(), request.getLocale(), virtualWiki,
            WikiBase.SPECIAL_PAGE_SYSTEM_CSS, false);
    stylesheet += '\n' + ServletUtil.cachedContent(request.getContextPath(), request.getLocale(), virtualWiki,
            WikiBase.SPECIAL_PAGE_CUSTOM_CSS, false);
    response.setContentType("text/css");
    response.setCharacterEncoding("UTF-8");
    // cache for 30 minutes (60 * 30 = 1800)
    // FIXME - make configurable
    response.setHeader("Cache-Control", "max-age=1800");
    PrintWriter out = response.getWriter();
    out.print(stylesheet);
    out.close();
    // do not load defaults or redirect - return as raw CSS
    return null;
}