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:main.java.vasolsim.common.file.ExamBuilder.java

/**
 * writes an editable, unlocked exam to a file
 *
 * @param exam      the exam to be written
 * @param examFile  the target file/*from   ww w.j a  v  a  2  s.  c  om*/
 * @param overwrite if an existing file can be overwritten
 *
 * @return if the file write was successful
 *
 * @throws VaSolSimException
 */
public static boolean writeRaw(@Nonnull Exam exam, @Nonnull File examFile, boolean overwrite)
        throws VaSolSimException {
    /*
     * check the file creation status and handle it
     */
    //if it exists
    if (examFile.isFile()) {
        //can't overwrite
        if (!overwrite) {
            throw new VaSolSimException(ERROR_MESSAGE_FILE_ALREADY_EXISTS);
        }
        //can overwrite, clear the existing file
        else {
            PrintWriter printWriter;
            try {
                printWriter = new PrintWriter(examFile);
            } catch (FileNotFoundException e) {
                throw new VaSolSimException(ERROR_MESSAGE_FILE_NOT_FOUND_AFTER_INTERNAL_CHECK);
            }

            printWriter.print("");
            printWriter.close();
        }
    }
    //no file, create one
    else {
        if (!examFile.getParentFile().isDirectory() && !examFile.getParentFile().mkdirs()) {
            throw new VaSolSimException(ERROR_MESSAGE_COULD_NOT_CREATE_DIRS);
        }

        try {
            if (!examFile.createNewFile()) {
                throw new VaSolSimException(ERROR_MESSAGE_COULD_NOT_CREATE_FILE);
            }
        } catch (IOException e) {
            throw new VaSolSimException(ERROR_MESSAGE_CREATE_FILE_EXCEPTION);
        }
    }

    /*
     * initialize the document
     */
    Document examDoc;
    Transformer examTransformer;
    try {
        examDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();

        examTransformer = TransformerFactory.newInstance().newTransformer();
        examTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
        examTransformer.setOutputProperty(OutputKeys.METHOD, "xml");
        examTransformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        examTransformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "roles.dtd");
        examTransformer.setOutputProperty(INDENTATION_KEY, "4");
    } catch (ParserConfigurationException e) {
        throw new VaSolSimException(ERROR_MESSAGE_INTERNAL_XML_PARSER_INITIALIZATION_EXCEPTION, e);
    } catch (TransformerConfigurationException e) {
        throw new VaSolSimException(ERROR_MESSAGE_INTERNAL_TRANSFORMER_CONFIGURATION, e);
    }

    /*
     * build exam info
     */
    Element root = examDoc.createElement(XML_ROOT_ELEMENT_NAME);
    examDoc.appendChild(root);

    Element info = examDoc.createElement(XML_INFO_ELEMENT_NAME);
    root.appendChild(info);

    //exam info
    GenericUtils.appendSubNode(XML_TEST_NAME_ELEMENT_NAME, exam.getTestName(), info, examDoc);
    GenericUtils.appendSubNode(XML_AUTHOR_NAME_ELEMENT_NAME, exam.getAuthorName(), info, examDoc);
    GenericUtils.appendSubNode(XML_SCHOOL_NAME_ELEMENT_NAME, exam.getSchoolName(), info, examDoc);
    GenericUtils.appendSubNode(XML_PERIOD_NAME_ELEMENT_NAME, exam.getPeriodName(), info, examDoc);

    //start security xml section
    Element security = examDoc.createElement(XML_SECURITY_ELEMENT_NAME);
    root.appendChild(security);

    GenericUtils.appendSubNode(XML_IS_REPORTING_STATISTICS_ELEMENT_NAME,
            Boolean.toString(exam.isReportingStats()), security, examDoc);
    GenericUtils.appendSubNode(XML_IS_REPORTING_STATISTICS_STANDALONE_ELEMENT_NAME,
            Boolean.toString(exam.isReportingStatsStandalone()), security, examDoc);
    GenericUtils.appendSubNode(XML_STATISTICS_DESTINATION_EMAIL_ADDRESS_ELEMENT_NAME,
            exam.getStatsDestinationEmail(), security, examDoc);
    GenericUtils.appendSubNode(XML_STATISTICS_SENDER_EMAIL_ADDRESS_ELEMENT_NAME, exam.getStatsSenderEmail(),
            security, examDoc);
    GenericUtils.appendSubNode(XML_STATISTICS_SENDER_SMTP_ADDRESS_ELEMENT_NAME,
            exam.getStatsSenderSMTPAddress(), security, examDoc);
    GenericUtils.appendSubNode(XML_STATISTICS_SENDER_SMTP_PORT_ELEMENT_NAME,
            Integer.toString(exam.getStatsSenderSMTPPort()), security, examDoc);

    ArrayList<QuestionSet> questionSets = exam.getQuestionSets();
    if (GenericUtils.verifyQuestionSetsIntegrity(questionSets)) {
        for (int setsIndex = 0; setsIndex < questionSets.size(); setsIndex++) {
            QuestionSet qSet = questionSets.get(setsIndex);

            Element qSetElement = examDoc.createElement(XML_QUESTION_SET_ELEMENT_NAME);
            root.appendChild(qSetElement);

            GenericUtils.appendSubNode(XML_QUESTION_SET_ID_ELEMENT_NAME, Integer.toString(setsIndex + 1),
                    qSetElement, examDoc);
            GenericUtils.appendSubNode(XML_QUESTION_SET_NAME_ELEMENT_NAME,
                    (qSet.getName() == null || qSet.getName().equals("")) ? "Question Set " + (setsIndex + 1)
                            : qSet.getName(),
                    qSetElement, examDoc);
            GenericUtils.appendSubNode(XML_QUESTION_SET_RESOURCE_TYPE_ELEMENT_NAME,
                    qSet.getResourceType().toString(), qSetElement, examDoc);

            if (qSet.getResources() != null) {
                for (BufferedImage img : qSet.getResources()) {
                    try {
                        ByteArrayOutputStream out = new ByteArrayOutputStream();
                        ImageIO.write(img, "png", out);
                        out.flush();
                        GenericUtils.appendSubNode(XML_QUESTION_SET_RESOURCE_DATA_ELEMENT_NAME,
                                convertBytesToHexString(out.toByteArray()), qSetElement, examDoc);
                    } catch (IOException e) {
                        throw new VaSolSimException("Error: cannot write images to byte array for transport");
                    }
                }
            }

            for (int setIndex = 0; setIndex < qSet.getQuestions().size(); setIndex++) {
                Question question = qSet.getQuestions().get(setIndex);

                Element qElement = examDoc.createElement(XML_QUESTION_ELEMENT_NAME);
                qSetElement.appendChild(qElement);

                GenericUtils.appendSubNode(XML_QUESTION_ID_ELEMENT_NAME, Integer.toString(setIndex + 1),
                        qElement, examDoc);
                GenericUtils.appendSubNode(XML_QUESTION_NAME_ELEMENT_NAME,
                        (question.getName() == null || question.getName().equals(""))
                                ? "Question " + (setIndex + 1)
                                : question.getName(),
                        qElement, examDoc);
                GenericUtils.appendSubNode(XML_QUESTION_TEXT_ELEMENT_NAME, question.getQuestion(), qElement,
                        examDoc);
                GenericUtils.appendSubNode(XML_QUESTION_SCRAMBLE_ANSWERS_ELEMENT_NAME,
                        Boolean.toString(question.getScrambleAnswers()), qElement, examDoc);
                GenericUtils.appendSubNode(XML_QUESTION_REATIAN_ANSWER_ORDER_ELEMENT_NAME,
                        Boolean.toString(question.getAnswerOrderMatters()), qElement, examDoc);

                for (AnswerChoice answer : question.getCorrectAnswerChoices()) {
                    GenericUtils.appendSubNode(XML_QUESTION_ENCRYPTED_ANSWER_HASH, answer.getAnswerText(),
                            qElement, examDoc);
                }

                for (int questionIndex = 0; questionIndex < question.getAnswerChoices()
                        .size(); questionIndex++) {
                    AnswerChoice ac = question.getAnswerChoices().get(questionIndex);

                    Element acElement = examDoc.createElement(XML_ANSWER_CHOICE_ELEMENT_NAME);
                    qElement.appendChild(acElement);

                    GenericUtils.appendSubNode(XML_ANSWER_CHOICE_ID_ELEMENT_NAME,
                            Integer.toString(questionIndex + 1), acElement, examDoc);
                    GenericUtils.appendSubNode(XML_ANSWER_CHOICE_VISIBLE_ID_ELEMENT_NAME,
                            ac.getVisibleChoiceID(), acElement, examDoc);
                    GenericUtils.appendSubNode(XML_ANSWER_TEXT_ELEMENT_NAME, ac.getAnswerText(), acElement,
                            examDoc);
                }
            }
        }
    }

    return true;
}

From source file:MainClass.java

public void run() {
      try {/*from  w w w  .java 2s .  c o m*/
          BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
          PrintWriter pw = new PrintWriter(sock.getOutputStream());

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

From source file:Copyright.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException {

    java.io.PrintWriter out = response.getWriter();
    out.println("Copyright&copy; 2003-2004 Java Source and Support.");
    out.close();

}

From source file:be.fedict.eid.idp.sp.PublicKeyServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    LOG.debug("doGet");
    String pemPrivate;//from w  w  w .  j av a 2 s  .  c  o m
    try {
        pemPrivate = toPem(PkiServlet.getPrivateKeyEntry().getCertificate().getPublicKey());
    } catch (Exception e) {
        LOG.error(e);
        return;
    }

    response.setContentType("text/plain");
    PrintWriter out = response.getWriter();
    out.print(pemPrivate);
    out.close();
}

From source file:com.bitranger.parknshop.seller.controller.SellerApplyShopCtrl.java

@RequestMapping(value = "/seller/applyShop", method = RequestMethod.GET)
public void applyShop(HttpServletRequest request, HttpServletResponse response) throws IOException {

    PsSeller psSeller = (PsSeller) request.getSession().getAttribute("currentSeller");

    String message = request.getParameter("msg");

    PsShopApply psShopApply = new PsShopApply();
    psShopApply.setIdSeller(psSeller.getId());
    psShopApply.setMessage(message);/*from  w w w .j  a  va 2  s .c  om*/
    psShopApply.setTimeCreated(new Timestamp(System.currentTimeMillis()));

    psShopApplyDAO.save(psShopApply);

    PrintWriter out = response.getWriter();
    out.write("success");
    out.flush();
    out.close();
}

From source file:com.betfair.tornjak.monitor.service.InOutServiceMonitor.java

protected void writeLine(String s, File f) throws FileNotFoundException {
    PrintWriter pw = new PrintWriter(f);
    pw.println(s);/*from w  ww. ja  va2 s.  com*/
    pw.close();
}

From source file:de.tudarmstadt.tk.statistics.importer.ExternalResultsReader.java

public static void readMUGCCV(String filePath) {
    String outFileName = "AggregatedTrainTest.csv";

    logger.log(Level.INFO, String.format("Importing data from directory %s.", filePath));

    // Method requires input directory. Check this condition.
    File directory = new File(filePath);
    if (directory.isDirectory()) {
        System.err.println("Please specify a file. Aborting.");
        return;//  ww  w  .  j  av  a 2  s.  co m
    }

    //Empty previous output file, if there was one
    File outputFile = new File(directory.getParentFile(), outFileName);
    if (outputFile.exists()) {
        outputFile.delete();
    }
    try {
        String header = "Train;Test;Classifier;FeatureSet;Measure;Value";

        PrintWriter out = new PrintWriter(new FileWriter(outputFile, true));
        out.println(header);
        out.close();
    } catch (IOException e) {
        System.err.println("Error while writing aggregated Train-Test file.");
        e.printStackTrace();
    }

    ArrayList<String> outputRows = new ArrayList<String>();

    // iterate all rows
    List<String[]> inputRowsFirstFile = new ArrayList<>();
    inputRowsFirstFile = readAndCheckCSV(filePath, ';');

    // first: order by train set
    ArrayList<ExternalResults> extResults = new ArrayList<>();

    for (int i = 0; i < inputRowsFirstFile.size(); i++) {
        ExternalResults results = new ExternalResults();

        // identify current train/test split
        String[] datasetNames = inputRowsFirstFile.get(i)[0].split(",");
        results.trainSetName = datasetNames[0].replace("CV: ", "").replace(" ", "");

        // set classifier name
        results.classifierParameters = inputRowsFirstFile.get(i)[1];

        // read feature set
        results.featureSetName = inputRowsFirstFile.get(i)[2];

        // read classification results
        results.recall = Double.parseDouble(inputRowsFirstFile.get(i)[3]);
        results.fMeasure = Double.parseDouble(inputRowsFirstFile.get(i)[4]);
        results.precision = Double.parseDouble(inputRowsFirstFile.get(i)[5]);
        results.accuracy = Double.parseDouble(inputRowsFirstFile.get(i)[10]) / 100;

        extResults.add(results);
    }

    HashMap<String, ArrayList<ExternalResults>> extResultsByTrainTestFeature = new HashMap<>();

    // order by test set
    for (ExternalResults result : extResults) {
        String IdKey = result.trainSetName + result.testSetName + result.featureSetName;

        if (extResultsByTrainTestFeature.containsKey(IdKey)) {
            extResultsByTrainTestFeature.get(IdKey).add(result);
        } else {
            extResultsByTrainTestFeature.put(IdKey, new ArrayList<ExternalResults>());
            extResultsByTrainTestFeature.get(IdKey).add(result);
        }
    }

    ArrayList<ExternalResults> aggregatedResults = new ArrayList<>();

    // aggregate results or keep as are
    for (Entry<String, ArrayList<ExternalResults>> trainTestSplit : extResultsByTrainTestFeature.entrySet()) {
        ExternalResults aggrResult = new ExternalResults();

        double recall = 0;
        double fMeasure = 0;
        double precision = 0;
        double accuracy = 0;
        int nrClassifiers = 0;

        // for all entries that are from the same train/test split and use the same feature set -> aggregate results
        for (ExternalResults result : trainTestSplit.getValue()) {
            aggrResult.testSetName = result.testSetName;
            aggrResult.trainSetName = result.trainSetName;
            aggrResult.classifierParameters = result.classifierParameters;
            aggrResult.featureSetName = result.featureSetName;

            recall += result.recall;
            fMeasure += result.fMeasure;
            precision += result.precision;
            accuracy += result.accuracy;
            nrClassifiers++;
        }

        aggrResult.accuracy = (accuracy / nrClassifiers);
        aggrResult.fMeasure = (fMeasure / nrClassifiers);
        aggrResult.recall = (recall / nrClassifiers);
        aggrResult.precision = (precision / nrClassifiers);

        aggregatedResults.add(aggrResult);
    }

    // write values of measure
    for (ExternalResults result : aggregatedResults) {
        String outputRow = String.format("%s;%s;%s;%s;%s;%s", result.trainSetName, result.testSetName, "0",
                result.featureSetName, "Percent Correct", result.accuracy);
        outputRows.add(outputRow);

        outputRow = String.format("%s;%s;%s;%s;%s;%s", result.trainSetName, result.testSetName, "0",
                result.featureSetName, "Weighted Precision", result.precision);
        outputRows.add(outputRow);

        outputRow = String.format("%s;%s;%s;%s;%s;%s", result.trainSetName, result.testSetName, "0",
                result.featureSetName, "Weighted Recall", result.recall);
        outputRows.add(outputRow);

        outputRow = String.format("%s;%s;%s;%s;%s;%s", result.trainSetName, result.testSetName, "0",
                result.featureSetName, "Weighted F-Measure", result.fMeasure);
        outputRows.add(outputRow);

    }

    // Write aggregated data to a new file
    try {
        PrintWriter out = new PrintWriter(new FileWriter(outputFile, true));
        for (String s : outputRows) {
            out.println(s);
        }
        out.close();
    } catch (IOException e) {
        System.err.println("Error while writing aggregated Train-Test file.");
        e.printStackTrace();
    }

    logger.log(Level.INFO,
            String.format("Finished import. The aggregated data was written to %s.", outFileName));
}

From source file:LVCoref.MMAX2.java

public static void exportNeAnnotation(Document d, String export_filename) {
    PrintWriter out;
    try {/*from   w  ww  .j  a  v a  2 s  .c o m*/
        String eol = System.getProperty("line.separator");
        out = new PrintWriter(new FileWriter(export_filename));
        StringBuilder s = new StringBuilder();
        for (Node n : d.tree) {
            s.append(n.conll_fields.get(1));
            s.append("\t");
            s.append(n.conll_fields.get(3).charAt(0));
            s.append("\t");
            s.append(n.conll_fields.get(2));
            s.append("\t");
            s.append(n.conll_fields.get(4));
            s.append("\t");
            if (n.ne_annotation.length() == 0)
                n.ne_annotation = "O";
            s.append(n.ne_annotation);
            s.append(eol);
            if (n.sentEnd)
                s.append(eol);
        }
        out.print(s.toString());
        out.flush();
        out.close();
    } catch (IOException ex) {
        Logger.getLogger(Document.class.getName()).log(Level.SEVERE, null, ex);
        System.err.println("ERROR: couldn't create/open output conll file");
    }
}

From source file:DropReceivedLines.java

/** Process one file given only its name */
public void process(String fileName) throws IOException {
    File old = new File(fileName);
    String newFileName = fileName + ".TMP";
    File newf = new File(newFileName);
    BufferedReader is = new BufferedReader(new FileReader(fileName));
    PrintWriter p = new PrintWriter(new FileWriter(newFileName));
    process(is, p); // call other process(), below
    p.close();
    old.renameTo(tempFile);/*from   w  w w  .jav  a 2 s.  co  m*/
    newf.renameTo(old);
    tempFile.delete();
}

From source file:de.tudarmstadt.tk.statistics.importer.ExternalResultsReader.java

public static void readMUGCTrainTest(String filePath) {
    String outFileName = "AggregatedTrainTest.csv";

    logger.log(Level.INFO, String.format("Importing data from directory %s.", filePath));

    // Method requires input directory. Check this condition.
    File directory = new File(filePath);
    if (directory.isDirectory()) {
        System.err.println("Please specify a file. Aborting.");
        return;//from   w w w  .  ja  va 2 s .c  om
    }

    //Empty previous output file, if there was one
    File outputFile = new File(directory.getParentFile(), outFileName);
    if (outputFile.exists()) {
        outputFile.delete();
    }
    try {
        String header = "Train;Test;Classifier;FeatureSet;Measure;Value";

        PrintWriter out = new PrintWriter(new FileWriter(outputFile, true));
        out.println(header);
        out.close();
    } catch (IOException e) {
        System.err.println("Error while writing aggregated Train-Test file.");
        e.printStackTrace();
    }

    ArrayList<String> outputRows = new ArrayList<String>();

    // iterate all rows
    List<String[]> inputRowsFirstFile = new ArrayList<>();
    inputRowsFirstFile = readAndCheckCSV(filePath, ';');

    // first: order by train set
    ArrayList<ExternalResults> extResults = new ArrayList<>();

    for (int i = 0; i < inputRowsFirstFile.size(); i++) {
        ExternalResults results = new ExternalResults();

        // identify current train/test split
        String[] datasetNames = inputRowsFirstFile.get(i)[0].replace("TRAIN:", "").replace("TEST:", "")
                .split(",");
        results.trainSetName = datasetNames[0].replace(" ", "");
        results.testSetName = datasetNames[1].replace(" ", "");

        // set classifier name
        results.classifierParameters = inputRowsFirstFile.get(i)[1];

        // read feature set
        results.featureSetName = inputRowsFirstFile.get(i)[2];

        // read classification results
        results.recall = Double.parseDouble(inputRowsFirstFile.get(i)[3]);
        results.fMeasure = Double.parseDouble(inputRowsFirstFile.get(i)[4]);
        results.precision = Double.parseDouble(inputRowsFirstFile.get(i)[5]);
        results.accuracy = Double.parseDouble(inputRowsFirstFile.get(i)[10]) / 100;

        extResults.add(results);
    }

    HashMap<String, ArrayList<ExternalResults>> extResultsByTrainTestFeature = new HashMap<>();

    // order by test set
    for (ExternalResults result : extResults) {
        String IdKey = result.trainSetName + result.testSetName + result.featureSetName;

        if (extResultsByTrainTestFeature.containsKey(IdKey)) {
            extResultsByTrainTestFeature.get(IdKey).add(result);
        } else {
            extResultsByTrainTestFeature.put(IdKey, new ArrayList<ExternalResults>());
            extResultsByTrainTestFeature.get(IdKey).add(result);
        }
    }

    ArrayList<ExternalResults> aggregatedResults = new ArrayList<>();

    // aggregate results or keep as are
    for (Entry<String, ArrayList<ExternalResults>> trainTestSplit : extResultsByTrainTestFeature.entrySet()) {
        ExternalResults aggrResult = new ExternalResults();

        double recall = 0;
        double fMeasure = 0;
        double precision = 0;
        double accuracy = 0;
        int nrClassifiers = 0;

        // for all entries that are from the same train/test split and use the same feature set -> aggregate results
        for (ExternalResults result : trainTestSplit.getValue()) {
            aggrResult.testSetName = result.testSetName;
            aggrResult.trainSetName = result.trainSetName;
            aggrResult.classifierParameters = result.classifierParameters;
            aggrResult.featureSetName = result.featureSetName;

            recall += result.recall;
            fMeasure += result.fMeasure;
            precision += result.precision;
            accuracy += result.accuracy;
            nrClassifiers++;
        }

        aggrResult.accuracy = (accuracy / nrClassifiers);
        aggrResult.fMeasure = (fMeasure / nrClassifiers);
        aggrResult.recall = (recall / nrClassifiers);
        aggrResult.precision = (precision / nrClassifiers);

        aggregatedResults.add(aggrResult);
    }

    // write values of measure
    for (ExternalResults result : aggregatedResults) {
        String outputRow = String.format("%s;%s;%s;%s;%s;%s", result.trainSetName, result.testSetName, "0",
                result.featureSetName, "Percent Correct", result.accuracy);
        outputRows.add(outputRow);

        outputRow = String.format("%s;%s;%s;%s;%s;%s", result.trainSetName, result.testSetName, "0",
                result.featureSetName, "Weighted Precision", result.precision);
        outputRows.add(outputRow);

        outputRow = String.format("%s;%s;%s;%s;%s;%s", result.trainSetName, result.testSetName, "0",
                result.featureSetName, "Weighted Recall", result.recall);
        outputRows.add(outputRow);

        outputRow = String.format("%s;%s;%s;%s;%s;%s", result.trainSetName, result.testSetName, "0",
                result.featureSetName, "Weighted F-Measure", result.fMeasure);
        outputRows.add(outputRow);

    }

    // Write aggregated data to a new file
    try {
        PrintWriter out = new PrintWriter(new FileWriter(outputFile, true));
        for (String s : outputRows) {
            out.println(s);
        }
        out.close();
    } catch (IOException e) {
        System.err.println("Error while writing aggregated Train-Test file.");
        e.printStackTrace();
    }

    logger.log(Level.INFO,
            String.format("Finished import. The aggregated data was written to %s.", outFileName));
}