Example usage for java.io PrintStream close

List of usage examples for java.io PrintStream close

Introduction

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

Prototype

public void close() 

Source Link

Document

Closes the stream.

Usage

From source file:com.sap.prd.mobile.ios.mios.ForkerTest.java

@Test
public void testStraightForward() throws Exception {

    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    final PrintStream log = new PrintStream(out, true);

    try {/*w ww  .j  ava  2s. c o  m*/

        Forker.forkProcess(log, new File(".").getAbsoluteFile(), "echo", "Hello World");

    } finally {
        log.close();
    }

    Assert.assertEquals("Hello World\n", new String(out.toByteArray()));
}

From source file:com.sap.prd.mobile.ios.mios.ForkerTest.java

@Test(expected = IllegalArgumentException.class)
public void testMissingArguments_3() throws Exception {

    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    final PrintStream log = new PrintStream(out, true);

    try {/*from   ww  w .j a  va2s  .  c  o m*/

        Forker.forkProcess(log, new File(".").getAbsoluteFile(), "echo", "", "Hello World");

    } finally {
        log.close();
    }
}

From source file:com.recomdata.datasetexplorer.proxy.HttpClient.java

/**
 * posts data to the inputstream and returns the InputStream.
 * @param postData data to be posted. must be url-encoded already.
 * @param contentType allows you to set the contentType of the request.
 * @return InputStream input stream from URLConnection
 *///from w ww . j a v  a2  s. co  m
public InputStream doPost(String postData, String contentType) {

    //   System.out.println("postdata:"+postData);
    //    System.out.println("ct:"+contentType);
    this.urlConnection.setDoOutput(true);
    if (contentType != null)
        this.urlConnection.setRequestProperty("Content-type", contentType);

    OutputStream os = this.getOutputStream();
    PrintStream ps = new PrintStream(os);
    ps.print(postData);
    ps.close();
    return (this.getInputStream());
}

From source file:com.sap.prd.mobile.ios.mios.ForkerTest.java

@Test(expected = IOException.class)
public void damagedPrintStream() throws Exception {

    final ByteArrayOutputStream out = new ByteArrayOutputStream();

    class DamagedPrintStream extends PrintStream {
        public DamagedPrintStream(OutputStream out) {
            super(out);
            setError();//from   ww  w  . j a va  2 s  .c  o  m
        }
    }
    final PrintStream log = new DamagedPrintStream(out);

    try {

        Forker.forkProcess(log, new File(".").getAbsoluteFile(), "echo", "Hello World");

    } finally {
        log.close();
    }
}

From source file:it.unipr.ce.dsg.s2p.peer.PeerListManager.java

/**
 * Write list to OutputStream (es. file). The format is JSON.
 * //w ww . j  a v a  2s.  c  om
 * @param ostream OutputStream
 * @return boolean return true if the OutputStream has been write
 */
synchronized public boolean writeList(OutputStream ostream) {

    try {
        JSONObject peerList = new JSONObject(this);

        //File newFile = new File(filePath+"cachelist.json");
        PrintStream printList = new PrintStream(ostream);
        printList.println(peerList.toString());
        printList.close();

    } catch (Exception e) {
        new RuntimeException(e);
        return false;
    }

    return true;
}

From source file:edu.emory.mathcs.nlp.zzz.CSVRadiology.java

public void tokenize(String inputFile, int outputStart) throws Exception {
    CSVParser parser = new CSVParser(IOUtils.createBufferedReader(inputFile), CSVFormat.DEFAULT);
    String inputPath = FileUtils.getPath(inputFile) + "/";
    List<CSVRecord> records = parser.getRecords();
    Tokenizer tokenizer = new EnglishTokenizer();

    P_BEFORE = new ArrayList<>();
    P_AFTER = new ArrayList<>();
    for (String s : BEFORE)
        P_BEFORE.add(new Pair<>(Pattern.compile(s), "\n" + s));
    for (String s : AFTER)
        P_AFTER.add(new Pair<>(Pattern.compile(s), s + "\n"));

    for (int i = 0; i < records.size(); i++) {
        PrintStream fout = IOUtils.createBufferedPrintStream(getOuputFilename(inputPath, i + outputStart));

        for (List<Token> tokens : tokenizer.segmentize(records.get(i).get(0)))
            print(fout, tokens);/*from   w ww .  j  a va2 s  .  c o  m*/

        fout.close();
    }

    parser.close();
}

From source file:jeeves.utils.Xml.java

/**
 * Loads an xml file from a URL after posting content to the URL.
 *
 * @param url/*w  w w .j av  a  2 s.c om*/
 * @param xmlQuery
 * @return
 * @throws IOException
 * @throws JDOMException
 */
public static Element loadFile(URL url, Element xmlQuery) throws IOException, JDOMException {
    Element result = null;
    try {
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/xml");
        connection.setRequestProperty("Content-Length",
                "" + Integer.toString(getString(xmlQuery).getBytes("UTF-8").length));
        connection.setRequestProperty("Content-Language", "en-US");
        connection.setDoOutput(true);
        PrintStream out = new PrintStream(connection.getOutputStream(), true, "UTF-8");
        out.print(getString(xmlQuery));
        out.close();

        SAXBuilder builder = getSAXBuilderWithoutXMLResolver(false);//new SAXBuilder();
        Document jdoc = builder.build(connection.getInputStream());

        result = (Element) jdoc.getRootElement().detach();
    } catch (Exception e) {
        Log.error(Log.ENGINE, "Error loading URL " + url.getPath() + " .Threw exception " + e);
        e.printStackTrace();
    }
    return result;
}

From source file:net.sf.vntconverter.VntConverter.java

/**
 * Dekodiert eine vNote-Datei in eine UTF-8-Textdatei.
 *///w  w  w. j ava2 s  .co m
private void decode(File in, File out) {
    FileInputStream inStream = null;
    try {
        inStream = new FileInputStream(in);
        BufferedReader br = new BufferedReader(new InputStreamReader(inStream, "UTF-8"));
        String line = null;
        String content = "";
        while ((line = br.readLine()) != null) {
            if (line.startsWith("BEGIN:")) {
            } else if (line.startsWith("VERSION:")) {
            } else if (line.startsWith("DCREATED:")) {
            } else if (line.startsWith("LAST-MODIFIED:")) {
            } else if (line.startsWith("END:VNOTE")) {
            } else if (line.startsWith("BODY;CHARSET=UTF-8;ENCODING=QUOTED-PRINTABLE:")) {
                content = line.substring("BODY;CHARSET=UTF-8;ENCODING=QUOTED-PRINTABLE:".length());
            } else {
                content += line;
            }
            if (content.endsWith("=")) {
                content = content.substring(0, content.length() - 1);
            }
        }
        br.close();
        PrintStream ps = new PrintStream(out, "UTF-8");
        ps.print(decode(content));
        ps.close();
    } catch (Exception e) {
        throw new RuntimeException("Exception caught in VntConverter.decode(in, out):", e);
    } finally {
        if (inStream != null) {
            try {
                inStream.close();
            } catch (IOException e) {
                // Einfach ignorieren ist hier ok
            }
        }
    }
}

From source file:admin.controller.ServletAddHtmlTemplate.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from w w w .  j a va  2 s  .c o m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
public void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    super.processRequest(request, response);
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    Layout layout = new Layout();
    String fileName = null, filePath = null, fieldName = null, uploadPath = null, uploadType = null;
    StringBuffer string_buffer = new StringBuffer();

    try {
        /* TODO output your page here. You may use following sample code. */
        uploadPath = AppConstants.BASE_HTML_TEMPLATE_UPLOAD_PATH;
        BufferedReader reader = request.getReader();
        String line = null;
        while ((line = reader.readLine()) != null) {
            string_buffer.append(line);
        }

        JSONParser parser = new JSONParser();
        JSONObject json_html_template = null;
        json_html_template = (JSONObject) parser.parse(string_buffer.toString());
        String type = (String) json_html_template.get("type");

        //            BufferedReader txtfile = new BufferedReader(new FileReader("c:\\test.txt"));
        String model_id = (String) json_html_template.get("model_id");
        String model_name = (String) json_html_template.get("model_name");
        String html_content = (String) json_html_template.get("html_content");

        fileName = model_name + ".html";
        filePath = uploadPath + File.separator + fileName;
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }
        OutputStream htmlfile = new FileOutputStream(new File(filePath));

        PrintStream printhtml = new PrintStream(htmlfile);

        layout.editModel(Integer.parseInt(model_id), fileName);

        printhtml.print(html_content);

        printhtml.close();
        htmlfile.close();
        out.write("true");
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "", ex);
        out.write(getSqlMethodsInstance().error);
    }
}

From source file:cc.wikitools.lucene.hadoop.FindWikipediaArticleIdHdfs.java

@SuppressWarnings("static-access")
@Override/*from  www  . j  a  v a2s .com*/
public int run(String[] args) throws Exception {
    Options options = new Options();
    options.addOption(
            OptionBuilder.withArgName("path").hasArg().withDescription("index location").create(INDEX_OPTION));
    options.addOption(
            OptionBuilder.withArgName("string").hasArg().withDescription("article title").create(TITLE_OPTION));

    CommandLine cmdline = null;
    CommandLineParser parser = new GnuParser();
    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (!cmdline.hasOption(TITLE_OPTION) || !cmdline.hasOption(INDEX_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(FindWikipediaArticleIdHdfs.class.getName(), options);
        System.exit(-1);
    }

    String indexLocation = cmdline.getOptionValue(INDEX_OPTION);
    String title = cmdline.getOptionValue(TITLE_OPTION);

    PrintStream out = new PrintStream(System.out, true, "UTF-8");

    HdfsWikipediaSearcher searcher = new HdfsWikipediaSearcher(new Path(indexLocation), getConf());
    int id = searcher.getArticleId(title);

    out.println(title + ": id = " + id);

    searcher.close();
    out.close();

    return 0;
}