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:playground.christoph.evacuation.analysis.AgentsInEvacuationAreaActivityWriter.java

/**
 * Writes the gathered data tab-separated into a text file.
 *
 * @param filename The name of a file where to write the gathered data.
 *///from   ww w.ja  v  a2s  . com
public void write(final String filename, int[] activities, int[] activitiesParticipatingAtHome,
        int[] activitiesParticipatingNotAtHome, int[] activitiesNotParticipatingAtHome,
        int[] activitiesNotParticipatingNotAtHome) {
    PrintStream stream;
    try {
        stream = new PrintStream(new File(filename));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return;
    }
    write(stream, activities, activitiesParticipatingAtHome, activitiesParticipatingNotAtHome,
            activitiesNotParticipatingAtHome, activitiesNotParticipatingNotAtHome);
    stream.close();
}

From source file:org.apache.pig.test.TestFilterOpNumeric.java

@Test
public void testNumericEq() throws Throwable {
    File tmpFile = File.createTempFile("test", "txt");
    PrintStream ps = new PrintStream(new FileOutputStream(tmpFile));
    for (int i = 0; i < LOOP_COUNT; i++) {
        if (i % 5 == 0) {
            ps.println(i + ":" + (double) i);
        } else {/*ww  w . j av a2 s  .  c  o  m*/
            ps.println(i + ":" + (i - 1));
        }
    }
    ps.close();
    pig.registerQuery("A=load '" + Util.encodeEscape(Util.generateURI(tmpFile.toString(), pig.getPigContext()))
            + "' using " + PigStorage.class.getName() + "(':');");
    String query = "A = filter A by ($0 == $1 and $0 <= $1);";
    log.info(query);
    pig.registerQuery(query);
    Iterator<Tuple> it = pig.openIterator("A");
    tmpFile.delete();
    while (it.hasNext()) {
        Tuple t = it.next();
        Double first = Double.valueOf(t.get(0).toString());
        Double second = Double.valueOf(t.get(1).toString());
        assertEquals(first, second);

        String sfirst = t.get(0).toString();
        String ssecond = t.get(1).toString();
        assertFalse(sfirst.equals(ssecond));
    }
}

From source file:org.apache.hadoop.hdfs.tools.TestGetConf.java

private String runTool(HdfsConfiguration conf, String[] args, boolean success) throws Exception {
    ByteArrayOutputStream o = new ByteArrayOutputStream();
    PrintStream out = new PrintStream(o, true);
    try {/*  www.  j  av a  2 s.  c om*/
        int ret = ToolRunner.run(new GetConf(conf, out, out), args);
        assertEquals(success, ret == 0);
        return o.toString();
    } finally {
        o.close();
        out.close();
    }
}

From source file:org.apache.mahout.classifier.ConfusionMatrixDumper.java

@Override
public int run(String[] args) throws IOException {
    addInputOption();/* www.  jav  a 2s . c o m*/
    addOption("output", "o", "Output path", null); // AbstractJob output feature requires param
    addOption(DefaultOptionCreator.overwriteOption().create());
    addFlag("html", null, "Create complete HTML page");
    addFlag("text", null, "Dump simple text");
    Map<String, List<String>> parsedArgs = parseArguments(args);
    if (parsedArgs == null) {
        return -1;
    }

    Path inputPath = getInputPath();
    String outputFile = hasOption("output") ? getOption("output") : null;
    boolean text = parsedArgs.containsKey("--text");
    boolean wrapHtml = parsedArgs.containsKey("--html");
    PrintStream out = getPrintStream(outputFile);
    if (text) {
        exportText(inputPath, out);
    } else {
        exportTable(inputPath, out, wrapHtml);
    }
    out.flush();
    if (out != System.out) {
        out.close();
    }
    return 0;
}

From source file:org.apache.pig.test.TestFilterOpNumeric.java

@Test
public void testNumericGt() throws Throwable {
    File tmpFile = File.createTempFile("test", "txt");
    PrintStream ps = new PrintStream(new FileOutputStream(tmpFile));
    for (int i = 0; i < LOOP_COUNT; i++) {
        if (i % 5 == 0) {
            ps.println(i + ":" + (double) i);
        } else {/*from w  ww.ja  v a 2s .  co m*/
            ps.println(i + 1 + ":" + (double) (i));
        }
    }
    ps.close();
    pig.registerQuery("A=load '" + Util.encodeEscape(Util.generateURI(tmpFile.toString(), pig.getPigContext()))
            + "' using " + PigStorage.class.getName() + "(':') as (f1: double, f2:double);");
    String query = "A = filter A by ($0 > $1 and $0 >= $1);";

    log.info(query);
    pig.registerQuery(query);
    Iterator<Tuple> it = pig.openIterator("A");
    tmpFile.delete();
    while (it.hasNext()) {
        Tuple t = it.next();
        Double first = Double.valueOf(t.get(0).toString());
        Double second = Double.valueOf(t.get(1).toString());
        assertTrue(first.compareTo(second) > 0);
    }
}

From source file:org.apache.pig.test.TestFilterOpNumeric.java

@Test
public void testNumericLt() throws Throwable {
    File tmpFile = File.createTempFile("test", "txt");
    PrintStream ps = new PrintStream(new FileOutputStream(tmpFile));
    for (int i = 0; i < LOOP_COUNT; i++) {
        if (i % 5 == 0) {
            ps.println(i + ":" + (double) i);
        } else {//w ww  . j a  v a  2s . c  o  m
            ps.println(i + ":" + (double) (i + 1));
        }
    }
    ps.close();
    pig.registerQuery("A=load '" + Util.encodeEscape(Util.generateURI(tmpFile.toString(), pig.getPigContext()))
            + "' using " + PigStorage.class.getName() + "(':') as (a: double, b:double);");
    String query = "A = filter A by ($0 <= $1 and $0 < $1);";

    log.info(query);
    pig.registerQuery(query);
    Iterator<Tuple> it = pig.openIterator("A");
    tmpFile.delete();
    while (it.hasNext()) {
        Tuple t = it.next();
        Double first = Double.valueOf(t.get(0).toString());
        Double second = Double.valueOf(t.get(1).toString());
        assertTrue(first.compareTo(second) < 0);
    }

}

From source file:com.meetingninja.csse.database.UserDatabaseAdapter.java

/**
 * Registers a passed in User and returns that user with an assigned UserID
 *
 * @param registerMe/*w  ww .ja  v  a2  s .  co m*/
 * @param password
 * @return the passed-in user with an assigned ID by the server
 * @throws Exception
 */
public static User register(User registerMe, String password) throws Exception {
    // Server URL setup
    String _url = getBaseUri().build().toString();

    // Establish connection
    URL url = new URL(_url);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    // add request header
    conn.setRequestMethod(IRequest.POST);
    addRequestHeader(conn, true);

    // prepare POST payload
    ByteArrayOutputStream json = new ByteArrayOutputStream();
    // this type of print stream allows us to get a string easily
    PrintStream ps = new PrintStream(json);
    // Create a generator to build the JSON string
    JsonGenerator jgen = JFACTORY.createGenerator(ps, JsonEncoding.UTF8);

    password = Utilities.computeHash(password);
    // Build JSON Object
    jgen.writeStartObject();
    jgen.writeStringField(Keys.User.NAME, registerMe.getDisplayName());
    jgen.writeStringField("password", password);
    jgen.writeStringField(Keys.User.EMAIL, registerMe.getEmail());
    jgen.writeStringField(Keys.User.PHONE, registerMe.getPhone());
    jgen.writeStringField(Keys.User.COMPANY, registerMe.getCompany());
    jgen.writeStringField(Keys.User.TITLE, registerMe.getTitle());
    jgen.writeStringField(Keys.User.LOCATION, registerMe.getLocation());
    jgen.writeEndObject();
    jgen.close();

    // Get JSON Object payload from print stream
    String payload = json.toString("UTF8");
    ps.close();

    // Send payload
    int responseCode = sendPostPayload(conn, payload);
    String response = getServerResponse(conn);

    User createUser = new User(registerMe);

    /*
     * result should get valid={"userID":"##"}
     */
    String result = "";
    if (!response.isEmpty()) {
        JsonNode tree = MAPPER.readTree(response);
        if (!tree.has(Keys.User.ID)) {

            result = "duplicate email or username";
        } else {
            result = tree.get(Keys.User.ID).asText();
            createUser.setID(result);
        }
    }

    conn.disconnect();
    return createUser;
}

From source file:de.indiplex.javapt.JavAPT.java

public void removeSource(String source) throws FileNotFoundException {
    if (source.contains("apt.saurik.com")) {
        System.out.println("You cannot remove sauriks source!");
        return;//from w  w w  . j  a va  2  s . com
    }
    if (sourcesURLs.contains(source)) {
        sourcesURLs.remove(source);
        PrintStream pw = new PrintStream(fSources);
        for (String s : sourcesURLs) {
            pw.println(s);
        }
        pw.close();
        if (isGUI()) {
            mf.fillSources(sourcesURLs);
        }
    }
}

From source file:com.meetingninja.csse.database.UserDatabaseAdapter.java

public static User update(String userID, Map<String, String> key_values)
        throws JsonGenerationException, IOException, InterruptedException {
    // prepare POST payload
    ByteArrayOutputStream json = new ByteArrayOutputStream();
    // this type of print stream allows us to get a string easily
    PrintStream ps = new PrintStream(json);

    // Create a generator to build the JSON string
    JsonGenerator jgen = JFACTORY.createGenerator(ps, JsonEncoding.UTF8);
    for (String key : key_values.keySet()) {
        if (key.equals(Keys.User.EMAIL) && !Utilities.isValidEmailAddress(key_values.get(Keys.User.EMAIL)))
            throw new IOException("Error : [Update User] Incorrect email format");
        else {//from   w w  w .  ja v a  2  s . co  m
            jgen.flush();
            // Build JSON Object
            jgen.writeStartObject();
            jgen.writeStringField(Keys.User.ID, userID);
            jgen.writeStringField("field", key);
            jgen.writeStringField("value", key_values.get(key));
            jgen.writeEndObject();
            jgen.writeRaw("\f");
        }
    }

    jgen.close();
    // Get JSON Object payload from print stream
    String payload = json.toString("UTF8");
    ps.close();
    String[] payloads = payload.split("\f\\s*");

    Thread t = new Thread(new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.getLocalizedMessage();
            }
        }
    }));
    String response = "";
    for (String p : payloads) {
        t.run();
        response = updateHelper(p);
    }
    return parseUser(MAPPER.readTree(response));
}

From source file:com.act.lcms.plotter.WriteAndPlotMS1Results.java

public void plotScan(List<MS1.YZ> scan, String outPrefix, String fmt) throws IOException {
    String outPDF = outPrefix + "." + fmt;
    String outDATA = outPrefix + ".data";

    // Write data output to outfile
    PrintStream out = new PrintStream(new FileOutputStream(outDATA));

    // print out the spectra to outDATA
    for (MS1.YZ yz : scan) {
        out.format("%.4f\t%.4f\n", yz.getMZ(), yz.getIntensity());
        out.flush();//w ww . java2  s .  c  om
    }

    // close the .data
    out.close();

    // render outDATA to outPDF using gnuplot
    new Gnuplotter().plot2DImpulsesWithLabels(outDATA, outPDF, new String[] { "mz distribution at TIC max" },
            null, "mz", null, "intensity", fmt);
}