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:org.apache.hadoop.fs.TestDFSIO.java

private static void analyzeResult(FileSystem fs, int testType, long execTime, String resFileName)
        throws IOException {
    Path reduceFile;/*from w  w w  . ja  va  2 s  . c  o  m*/
    if (testType == TEST_TYPE_WRITE)
        reduceFile = new Path(WRITE_DIR, "part-00000");
    else
        reduceFile = new Path(READ_DIR, "part-00000");
    long tasks = 0;
    long size = 0;
    long time = 0;
    float rate = 0;
    float sqrate = 0;
    DataInputStream in = null;
    BufferedReader lines = null;
    try {
        in = new DataInputStream(fs.open(reduceFile));
        lines = new BufferedReader(new InputStreamReader(in));
        String line;
        while ((line = lines.readLine()) != null) {
            StringTokenizer tokens = new StringTokenizer(line, " \t\n\r\f%");
            String attr = tokens.nextToken();
            if (attr.endsWith(":tasks"))
                tasks = Long.parseLong(tokens.nextToken());
            else if (attr.endsWith(":size"))
                size = Long.parseLong(tokens.nextToken());
            else if (attr.endsWith(":time"))
                time = Long.parseLong(tokens.nextToken());
            else if (attr.endsWith(":rate"))
                rate = Float.parseFloat(tokens.nextToken());
            else if (attr.endsWith(":sqrate"))
                sqrate = Float.parseFloat(tokens.nextToken());
        }
    } finally {
        if (in != null)
            in.close();
        if (lines != null)
            lines.close();
    }

    double med = rate / 1000 / tasks;
    double stdDev = Math.sqrt(Math.abs(sqrate / 1000 / tasks - med * med));
    String resultLines[] = { "----- TestDFSIO ----- : "
            + ((testType == TEST_TYPE_WRITE) ? "write" : (testType == TEST_TYPE_READ) ? "read" : "unknown"),
            "           Date & time: " + new Date(System.currentTimeMillis()),
            "       Number of files: " + tasks, "Total MBytes processed: " + size / MEGA,
            "     Throughput mb/sec: " + size * 1000.0 / (time * MEGA), "Average IO rate mb/sec: " + med,
            " IO rate std deviation: " + stdDev, "    Test exec time sec: " + (float) execTime / 1000, "" };

    PrintStream res = null;
    try {
        res = new PrintStream(new FileOutputStream(new File(resFileName), true));
        for (int i = 0; i < resultLines.length; i++) {
            LOG.info(resultLines[i]);
            res.println(resultLines[i]);
        }
    } finally {
        if (res != null)
            res.close();
    }
}

From source file:edu.cmu.cs.lti.ark.fn.parsing.DataPrep.java

public static void writeFeatureIndex(String alphabetFilename) {
    int numFeatures = featureIndex.size();
    PrintStream printStream = FileUtil.openOutFile(alphabetFilename);
    printStream.println(numFeatures);// w  w  w .  jav  a 2s . c om
    String buf[] = new String[numFeatures + 1];
    for (String feature : featureIndex.keySet()) {
        buf[featureIndex.get(feature)] = feature;
    }
    for (int i = 1; i <= numFeatures; i++) {
        printStream.println(buf[i]);
    }
    printStream.close();
}

From source file:com.simiacryptus.util.Util.java

/**
 * Report.//from  w  ww .j  a  v a  2  s  .c  o m
 *
 * @param fragments the fragments
 * @throws IOException the io exception
 */
public static void report(@javax.annotation.Nonnull final Stream<String> fragments) throws IOException {
    @javax.annotation.Nonnull
    final File outDir = new File("reports");
    outDir.mkdirs();
    final StackTraceElement caller = com.simiacryptus.util.Util
            .getLast(Arrays.stream(Thread.currentThread().getStackTrace())//
                    .filter(x -> x.getClassName().contains("simiacryptus")));
    @javax.annotation.Nonnull
    final File report = new File(outDir, caller.getClassName() + "_" + caller.getLineNumber() + ".html");
    @javax.annotation.Nonnull
    final PrintStream out = new PrintStream(new FileOutputStream(report));
    out.println("<html><head></head><body>");
    fragments.forEach(out::println);
    out.println("</body></html>");
    out.close();
    Desktop.getDesktop().browse(report.toURI());
}

From source file:com.arcusys.liferay.vaadinplugin.util.WidgetsetUtil.java

/**
 * Creates a widgetset .gwt.xml file under a given directory.
 *
 * @param widgetset/*from w  w w  .j  a v  a2  s .c om*/
 *            the name of Widgetset. For example: com.example.TestWidgetSet
 * @throws java.io.IOException
 */
public static void createWidgetset(File tmpDir, String widgetset, Set<String> includeWidgetsets)
        throws IOException {

    String dir = widgetset.substring(0, widgetset.lastIndexOf(".")).replace(".",
            ControlPanelPortletUtil.FileSeparator);
    String file = widgetset.substring(widgetset.lastIndexOf(".") + 1, widgetset.length()) + ".gwt.xml";

    File widgetsetDir = new File(tmpDir, dir);
    if (!widgetsetDir.mkdirs()) {
        throw new IOException("Could not create dir: " + widgetsetDir.getAbsolutePath());
    }
    File widgetsetFile = new File(widgetsetDir, file);
    if (!widgetsetFile.createNewFile()) {
        throw new IOException("");
    }

    PrintStream printStream = new PrintStream(new FileOutputStream(widgetsetFile));
    printStream.print("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
            + "<!DOCTYPE module PUBLIC \"-//Google Inc.//DTD "
            + "Google Web Toolkit 1.7.0//EN\" \"http://google"
            + "-web-toolkit.googlecode.com/svn/tags/1.7.0/dis" + "tro-source/core/src/gwt-module.dtd\">\n");
    printStream.print("<module>\n");

    for (String ws : includeWidgetsets) {
        printStream.print("<inherits name=\"" + ws + "\" />\n");
    }

    printStream.print("\n</module>\n");
    printStream.close();
}

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

public static List<Contact> addContact(String contactUserID) throws IOException {

    String _url = getBaseUri().build().toString();
    URL url = new URL(_url);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod(IRequest.PUT);
    addRequestHeader(conn, false);/*from  w  ww.  ja v a2s  . c om*/
    SessionManager session = SessionManager.getInstance();
    String userID = session.getUserID();
    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);
    // Build JSON Object for Title
    jgen.writeStartObject();
    jgen.writeStringField(Keys.User.ID, userID);
    jgen.writeArrayFieldStart(Keys.User.CONTACTS);
    jgen.writeStartObject();
    jgen.writeStringField(Keys.User.CONTACTID, contactUserID);
    jgen.writeEndObject();
    jgen.writeEndArray();
    jgen.writeEndObject();
    jgen.close();
    String payload = json.toString("UTF8");
    ps.close();

    sendPostPayload(conn, payload);
    String response = getServerResponse(conn);

    // TODO: put add useful check here
    // User userContact=null;
    // String relationID=null;
    // String result = new String();
    // if (!response.isEmpty()) {
    // JsonNode contactNode = MAPPER.readTree(response);
    // if (!contactNode.has(Keys.User.ID)) {
    // result = "invalid";
    // } else {
    // result = contactNode.get(Keys.User.ID).asText();
    // userContact = getUserInfo(result);
    // relationID = contactNode.get(Keys.User.RELATIONID).asText();
    // }
    // }

    // if (!result.equalsIgnoreCase("invalid"))
    // g.setID(result);
    conn.disconnect();

    // Contact contact = new Contact(userContact,relationID);
    List<Contact> contacts = new ArrayList<Contact>();
    contacts = getContacts(userID);
    return contacts;
}

From source file:dk.netarkivet.common.utils.warc.WARCUtils.java

/**
 * Create new WARCWriter, writing to warcfile newFile.
 * @param newFile the WARCfile, that the WARCWriter writes to.
 * @return new WARCWriter, writing to warcfile newFile.
 *//*from  w ww  .  j av a  2 s .  c o m*/
public static WARCWriter createWARCWriter(File newFile) {
    WARCWriter writer;
    PrintStream ps = null;
    try {
        ps = new PrintStream(new FileOutputStream(newFile));
        writer = new WARCWriterNAS(new AtomicInteger(), ps,
                //This name is used for the first (file metadata) record
                newFile, false, //Don't compress
                //Use current time
                ArchiveDateConverter.getWarcDateFormat().format(new Date()), null //No particular file metadata to add
        );
    } catch (IOException e) {
        if (ps != null) {
            ps.close();
        }
        String message = "Could not create WARCWriter to file '" + newFile + "'.\n";
        log.warn(message);
        throw new IOFailure(message, e);
    }
    return writer;
}

From source file:dk.netarkivet.common.utils.arc.ARCUtils.java

/**
 * Create new ARCWriter, writing to arcfile newFile.
 * @param newFile the ARCfile, that the ARCWriter writes to.
 * @return new ARCWriter, writing to arcfile newFile.
 *///w w w  .  jav  a 2 s.c  om
public static ARCWriter createARCWriter(File newFile) {
    ARCWriter aw;
    PrintStream ps = null;
    try {
        ps = new PrintStream(new FileOutputStream(newFile));
        aw = new ARCWriter(new AtomicInteger(), ps,
                //This name is used for the first (file metadata) record
                newFile, false, //Don't compress
                //Use current time
                ArchiveUtils.get14DigitDate(System.currentTimeMillis()), null //No particular file metadata to add
        );
    } catch (IOException e) {
        if (ps != null) {
            ps.close();
        }
        String message = "Could not create ARCWriter to file '" + newFile + "'.\n";
        log.warn(message);
        throw new IOFailure(message, e);
    }
    return aw;
}

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

public static void updateProject(Project p) throws IOException {
    ByteArrayOutputStream json = new ByteArrayOutputStream();
    // this type of print stream allows us to get a string easily
    PrintStream ps = new PrintStream(json);
    JsonGenerator jgen = JFACTORY.createGenerator(ps, JsonEncoding.UTF8);
    // Build JSON Object for Title
    jgen.writeStartObject();//from ww  w.ja  v  a 2s .c o m
    jgen.writeStringField(Keys.Project.ID, p.getProjectID());
    jgen.writeStringField("field", Keys.Project.TITLE);
    jgen.writeStringField("value", p.getProjectTitle());
    jgen.writeEndObject();
    jgen.close();
    String payloadTitle = json.toString("UTF8");
    ps.close();

    json = new ByteArrayOutputStream();
    // this type of print stream allows us to get a string easily
    ps = new PrintStream(json);
    jgen = JFACTORY.createGenerator(ps, JsonEncoding.UTF8);
    // Build JSON Object for Project members
    jgen.writeStartObject();
    jgen.writeStringField(Keys.Project.ID, p.getProjectID());
    jgen.writeStringField("field", Keys.Project.MEETINGS);
    jgen.writeArrayFieldStart("value");
    for (Meeting meeting : p.getMeetings()) {
        jgen.writeStartObject();
        jgen.writeStringField(Keys.Meeting.ID, meeting.getID());
        jgen.writeEndObject();

    }
    jgen.writeEndArray();
    jgen.writeEndObject();
    jgen.close();
    String payloadMeetings = json.toString("UTF8");
    ps.close();

    json = new ByteArrayOutputStream();
    // this type of print stream allows us to get a string easily
    ps = new PrintStream(json);
    jgen = JFACTORY.createGenerator(ps, JsonEncoding.UTF8);
    // Build JSON Object for Project members
    jgen.writeStartObject();
    jgen.writeStringField(Keys.Project.ID, p.getProjectID());
    jgen.writeStringField("field", Keys.Project.NOTES);
    jgen.writeArrayFieldStart("value");
    for (Note note : p.getNotes()) {
        jgen.writeStartObject();
        jgen.writeStringField(Keys.Note.ID, note.getID());
        jgen.writeEndObject();

    }
    jgen.writeEndArray();
    jgen.writeEndObject();
    jgen.close();
    String payloadNotes = json.toString("UTF8");
    ps.close();

    json = new ByteArrayOutputStream();
    // this type of print stream allows us to get a string easily
    ps = new PrintStream(json);
    jgen = JFACTORY.createGenerator(ps, JsonEncoding.UTF8);
    // Build JSON Object for Project members
    jgen.writeStartObject();
    jgen.writeStringField(Keys.Project.ID, p.getProjectID());
    jgen.writeStringField("field", Keys.Project.MEMBERS);
    jgen.writeArrayFieldStart("value");
    for (User member : p.getMembers()) {
        jgen.writeStartObject();
        jgen.writeStringField(Keys.User.ID, member.getID());
        jgen.writeEndObject();

    }
    jgen.writeEndArray();
    jgen.writeEndObject();
    jgen.close();
    String payloadMembers = json.toString("UTF8");
    ps.close();

    // Establish connection
    updateHelper(payloadTitle);
    updateHelper(payloadMeetings);
    updateHelper(payloadNotes);
    System.out.println(updateHelper(payloadMembers));

}

From source file:edu.byu.softwareDist.manager.impl.SendEmailImpl.java

private static File saveTemplateToDisk(final FileSet fileSet) {
    File f = null;/* www  . ja  v a  2s .  co m*/
    PrintStream out = null;
    try {
        f = File.createTempFile("software-distribution-email-content." + fileSet.getFileSetId() + "-", ".vm");
        out = new PrintStream(new FileOutputStream(f));
        out.print(fileSet.getEmailContent());
        out.flush();
        return f;
    } catch (IOException e) {
        LOG.error("Error writing template to temporary file.", e);
        return null;
    } finally {
        if (f != null) {
            f.deleteOnExit();
        }
        if (out != null) {
            out.close();
        }
    }
}

From source file:NMTFUtils.GetFWords.java

public static void getTopWordsDTL(String base) throws IOException {
    int TOP_NUM = 20;
    List<String> dictsLists = FileUtils.readLines(new File(dicpath));
    List<String> indexLists = FileUtils.readLines(new File("F:\\matlab_code\\DTL\\indexs.csv"));
    Map<String, String> wordMaps = new HashMap<>();

    for (String line : dictsLists) {
        String[] split = line.split("@:@");
        if (split.length != 2) {
            wordMaps.put(split[0], "");
        } else {/*w  ww.  j a  v  a 2s .co  m*/
            wordMaps.put(split[0], split[1]);
        }

    }
    PrintStream ps = new PrintStream(
            "G:\\\\\\journal\\" + base + "\\DTLs-TopWords.txt");
    for (int li = 0; li < indexLists.size(); li++) {
        String[] split = indexLists.get(li).split(",");
        StringBuilder topWords = new StringBuilder();
        for (int i = 0; i < TOP_NUM; i++) {
            String get = wordMaps.get(split[i]);
            if (get != null) {
                topWords.append(get.trim()).append(" ");
            } else {
                System.out.println(split[i]);
                return;
            }
        }
        System.out.println(topWords);
        ps.println("TOP:" + (li + 1) + " " + topWords);
    }
    ps.flush();
    ps.close();

}