Example usage for java.io PrintWriter append

List of usage examples for java.io PrintWriter append

Introduction

In this page you can find the example usage for java.io PrintWriter append.

Prototype

public PrintWriter append(char c) 

Source Link

Document

Appends the specified character to this writer.

Usage

From source file:Main.java

public static void main(String[] args) {
    try {//from  w ww. jav  a  2s  .  c  om
        PrintWriter pw = new PrintWriter(new FileWriter("c:/text.txt"), true);

        // append chars
        pw.append('H');
        pw.append('e');
        pw.append('l');
        pw.append('l');
        pw.append('o');

        // flush the writer
        pw.flush();
        pw.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:org.xwiki.xdomviz.Main.java

/**
 * Entry point//from ww w .j a  v  a  2 s .c o  m
 */
public static void main(String[] args) throws Exception {
    // Parse command line
    Options options = new Options();
    options.addOption("n", false, "Normalize the XDOM");
    options.addOption("o", true, "Output file name");
    options.addOption("h", false, "Help");

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = parser.parse(options, args);

    if (cmd.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(String.format("%s [options] [input file]", Main.class.getName()),
                "If no input file is specified, standard input is used", options, "");
        return;
    }

    boolean normalize = false;
    if (cmd.hasOption("n")) {
        normalize = true;
    }

    String outputFileName = null;
    if (cmd.hasOption("o")) {
        outputFileName = cmd.getOptionValue("o");
    }

    String inputFileName = null;
    if (cmd.getArgs().length > 0) {
        inputFileName = cmd.getArgs()[0];
    }

    BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
    if (inputFileName != null) {
        input = new BufferedReader(new FileReader(new File(inputFileName)));
    }

    PrintWriter output = new PrintWriter(new OutputStreamWriter(System.out));
    if (outputFileName != null) {
        output = new PrintWriter(new FileWriter(new File(outputFileName)));
    }

    // Read the text to parse
    String text = readText(input);

    // Initialize Rendering components and allow getting instances
    EmbeddableComponentManager ecm = new EmbeddableComponentManager();
    ecm.initialize(ClassLoader.getSystemClassLoader());

    // Parse XWiki 2.0 Syntax using a Parser.
    Parser xdomParser = ecm.lookup(Parser.class, Syntax.XWIKI_2_0.toIdString());
    XDOM xdom = xdomParser.parse(new StringReader(text));

    // Create the "working" tree
    Node root = createNodeTree(xdom);

    // Normalize it if requested
    if (normalize) {
        root = normalize(root);
    }

    // Write the output
    output.append(generateGraphViz(root));

    // Close everything
    output.close();
    input.close();
}

From source file:com.ifeng.sorter.NginxApp.java

public static void main(String[] args) {

    String input = "src/test/resources/data/nginx_report.txt";

    PrintWriter pw = null;

    Map<String, List<LogBean>> resultMap = new HashMap<String, List<LogBean>>();
    List<String> ips = new ArrayList<String>();

    try {/*from   w  w  w.j av  a 2  s  . c  om*/
        List<String> lines = FileUtils.readLines(new File(input));
        List<LogBean> items = new ArrayList<LogBean>();

        for (String line : lines) {
            String[] values = line.split("\t");

            if (values != null && values.length == 3) {// ip total seria
                try {
                    String ip = values[0].trim();
                    String total = values[1].trim();
                    String seria = values[2].trim();

                    LogBean bean = new LogBean(ip, Integer.parseInt(total), seria);

                    items.add(bean);

                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }
        }

        Collections.sort(items);

        for (LogBean bean : items) {
            String key = bean.getIp();

            if (resultMap.containsKey(key)) {
                resultMap.get(key).add(bean);
            } else {
                List<LogBean> keyList = new ArrayList<LogBean>();
                keyList.add(bean);
                resultMap.put(key, keyList);

                ips.add(key);
            }
        }

        pw = new PrintWriter("src/test/resources/output/result.txt", "UTF-8");

        for (String ip : ips) {
            List<LogBean> list = resultMap.get(ip);

            for (LogBean bean : list) {
                pw.append(bean.toString());
                pw.println();
            }
        }

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        pw.flush();
        pw.close();
    }
}

From source file:ch.epfl.lsir.xin.test.ItemBasedCFTest.java

/**
 * @param args//from w ww  . j  a v a2 s  .  c o m
 */
public static void main(String[] args) throws Exception {
    // TODO Auto-generated method stub

    PrintWriter logger = new PrintWriter(".//results//ItemBasedCF");
    PropertiesConfiguration config = new PropertiesConfiguration();
    config.setFile(new File(".//conf//ItemBasedCF.properties"));
    try {
        config.load();
    } catch (ConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    logger.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " Read rating data...");
    DataLoaderFile loader = new DataLoaderFile(".//data//MoveLens100k.txt");
    loader.readSimple();
    DataSetNumeric dataset = loader.getDataset();
    System.out.println("Number of ratings: " + dataset.getRatings().size() + " Number of users: "
            + dataset.getUserIDs().size() + " Number of items: " + dataset.getItemIDs().size());
    logger.println("Number of ratings: " + dataset.getRatings().size() + ", Number of users: "
            + dataset.getUserIDs().size() + ", Number of items: " + dataset.getItemIDs().size());
    logger.flush();

    double totalMAE = 0;
    double totalRMSE = 0;
    double totalPrecision = 0;
    double totalRecall = 0;
    double totalMAP = 0;
    double totalNDCG = 0;
    double totalMRR = 0;
    double totalAUC = 0;
    int F = 5;
    logger.println(F + "- folder cross validation.");
    ArrayList<ArrayList<NumericRating>> folders = new ArrayList<ArrayList<NumericRating>>();
    for (int i = 0; i < F; i++) {
        folders.add(new ArrayList<NumericRating>());
    }

    while (dataset.getRatings().size() > 0) {
        int index = new Random().nextInt(dataset.getRatings().size());
        int r = new Random().nextInt(F);
        folders.get(r).add(dataset.getRatings().get(index));
        dataset.getRatings().remove(index);
    }

    for (int folder = 1; folder <= F; folder++) {
        logger.println("Folder: " + folder);
        System.out.println("Folder: " + folder);
        ArrayList<NumericRating> trainRatings = new ArrayList<NumericRating>();
        ArrayList<NumericRating> testRatings = new ArrayList<NumericRating>();
        for (int i = 0; i < folders.size(); i++) {
            if (i == folder - 1)//test data
            {
                testRatings.addAll(folders.get(i));
            } else {//training data
                trainRatings.addAll(folders.get(i));
            }
        }

        //create rating matrix
        HashMap<String, Integer> userIDIndexMapping = new HashMap<String, Integer>();
        HashMap<String, Integer> itemIDIndexMapping = new HashMap<String, Integer>();
        for (int i = 0; i < dataset.getUserIDs().size(); i++) {
            userIDIndexMapping.put(dataset.getUserIDs().get(i), i);
        }
        for (int i = 0; i < dataset.getItemIDs().size(); i++) {
            itemIDIndexMapping.put(dataset.getItemIDs().get(i), i);
        }
        RatingMatrix trainRatingMatrix = new RatingMatrix(dataset.getUserIDs().size(),
                dataset.getItemIDs().size());
        for (int i = 0; i < trainRatings.size(); i++) {
            trainRatingMatrix.set(userIDIndexMapping.get(trainRatings.get(i).getUserID()),
                    itemIDIndexMapping.get(trainRatings.get(i).getItemID()), trainRatings.get(i).getValue());
        }
        trainRatingMatrix.calculateGlobalAverage();
        trainRatingMatrix.calculateItemsMean();
        RatingMatrix testRatingMatrix = new RatingMatrix(dataset.getUserIDs().size(),
                dataset.getItemIDs().size());
        for (int i = 0; i < testRatings.size(); i++) {
            testRatingMatrix.set(userIDIndexMapping.get(testRatings.get(i).getUserID()),
                    itemIDIndexMapping.get(testRatings.get(i).getItemID()), testRatings.get(i).getValue());
        }
        System.out.println("Training: " + trainRatingMatrix.getTotalRatingNumber() + " vs Test: "
                + testRatingMatrix.getTotalRatingNumber());
        logger.println("Initialize a item based collaborative filtering recommendation model.");
        ItemBasedCF algo = new ItemBasedCF(trainRatingMatrix);
        algo.setLogger(logger);
        algo.build();//if read local model, no need to build the model
        algo.saveModel(".//localModels//" + config.getString("NAME"));
        logger.println("Save the model.");
        logger.flush();

        //rating prediction accuracy
        double RMSE = 0;
        double MAE = 0;
        double precision = 0;
        double recall = 0;
        double map = 0;
        double ndcg = 0;
        double mrr = 0;
        double auc = 0;
        int count = 0;
        for (int i = 0; i < testRatings.size(); i++) {
            NumericRating rating = testRatings.get(i);
            double prediction = algo.predict(userIDIndexMapping.get(rating.getUserID()),
                    itemIDIndexMapping.get(rating.getItemID()), false);
            if (prediction > algo.getMaxRating())
                prediction = algo.getMaxRating();
            if (prediction < algo.getMinRating())
                prediction = algo.getMinRating();

            if (Double.isNaN(prediction)) {
                System.out.println("no prediction");
                continue;
            }
            MAE = MAE + Math.abs(rating.getValue() - prediction);
            RMSE = RMSE + Math.pow((rating.getValue() - prediction), 2);
            count++;
        }
        MAE = MAE / count;
        RMSE = Math.sqrt(RMSE / count);
        totalMAE = totalMAE + MAE;
        totalRMSE = totalRMSE + RMSE;
        System.out.println("Folder --- MAE: " + MAE + " RMSE: " + RMSE);
        logger.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " Folder --- MAE: "
                + MAE + " RMSE: " + RMSE);

        //ranking accuracy
        if (algo.getTopN() > 0) {
            HashMap<Integer, ArrayList<ResultUnit>> results = new HashMap<Integer, ArrayList<ResultUnit>>();
            for (int i = 0; i < trainRatingMatrix.getRow(); i++) {
                //               ArrayList<ResultUnit> rec = algo.getRecommendationList(i);
                //               results.put(i, rec);
                ArrayList<ResultUnit> rec = algo.getRecommendationList(i);
                if (rec == null)
                    continue;
                int total = testRatingMatrix.getUserRatingNumber(i);
                if (total == 0)//this user is ignored
                    continue;
                results.put(i, rec);
            }
            RankResultGenerator generator = new RankResultGenerator(results, algo.getTopN(), testRatingMatrix,
                    trainRatingMatrix);
            precision = generator.getPrecisionN();
            totalPrecision = totalPrecision + precision;
            recall = generator.getRecallN();
            totalRecall = totalRecall + recall;
            map = generator.getMAPN();
            totalMAP = totalMAP + map;
            ndcg = generator.getNDCGN();
            totalNDCG = totalNDCG + ndcg;
            mrr = generator.getMRRN();
            totalMRR = totalMRR + mrr;
            auc = generator.getAUC();
            totalAUC = totalAUC + auc;
            System.out.println("Folder --- precision: " + precision + " recall: " + recall + " map: " + map
                    + " ndcg: " + ndcg + " mrr: " + mrr + " auc: " + auc);
            logger.append("Folder --- precision: " + precision + " recall: " + recall + " map: " + map
                    + " ndcg: " + ndcg + " mrr: " + mrr + " auc: " + auc + "\n");
        }
    }

    System.out.println("MAE: " + totalMAE / F + " RMSE: " + totalRMSE / F);
    System.out.println("Precision@N: " + totalPrecision / F);
    System.out.println("Recall@N: " + totalRecall / F);
    System.out.println("MAP@N: " + totalMAP / F);
    System.out.println("MRR@N: " + totalMRR / F);
    System.out.println("NDCG@N: " + totalNDCG / F);
    System.out.println("AUC@N: " + totalAUC / F);
    System.out.println("similarity: " + config.getString("SIMILARITY"));
    //MAE: 0.7227232762922241 RMSE: 0.9225576790122603 (MovieLens 100K, shrinkage 2500, neighbor size 40, PCC)
    //MAE: 0.7250636319353241 RMSE: 0.9242305485411567 (MovieLens 100K, shrinkage 25, neighbor size 40, PCC)
    //MAE: 0.7477213243604459 RMSE: 0.9512195004171138 (MovieLens 100K, shrinkage 2500, neighbor size 40, COSINE)

    logger.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "\n" + "MAE: "
            + totalMAE / F + " RMSE: " + totalRMSE / F + "\n" + "Precision@N: " + totalPrecision / F + "\n"
            + "Recall@N: " + totalRecall / F + "\n" + "MAP@N: " + totalMAP / F + "\n" + "MRR@N: " + totalMRR / F
            + "\n" + "NDCG@N: " + totalNDCG / F + "\n" + "AUC@N: " + totalAUC / F);
    logger.flush();
    logger.close();
}

From source file:com.github.rnewson.couchdb.lucene.Utils.java

public static String error(final int code, final Throwable t) {
    final StringWriter writer = new StringWriter();
    final PrintWriter printWriter = new PrintWriter(writer);
    if (t.getMessage() != null) {
        printWriter.append(t.getMessage());
        printWriter.append("\n");
    }//  ww w.ja v a2  s  .c  om
    t.printStackTrace(printWriter);
    return new JSONObject().element("code", code).element("body", "<pre>" + writer + "</pre>").toString();
}

From source file:org.loklak.tools.NetworkIO.java

public static StringBuilder pushString(String requestURL, String jsonDataName, String bodytext)
        throws IOException, JSONException {
    String boundary = "===" + System.currentTimeMillis() + "===";

    URL url = new URL(requestURL);
    //HttpURLConnection con = (HttpURLConnection) url.openConnection();
    URLConnection uc = (url).openConnection();
    HttpURLConnection con = requestURL.startsWith("https") ? (HttpsURLConnection) uc : (HttpURLConnection) uc;
    con.setUseCaches(false);/*from  w  w w .j  a  va 2s .  com*/
    con.setDoOutput(true);
    con.setDoInput(true);
    con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
    con.setRequestProperty("User-Agent", USER_AGENT);
    OutputStream outputStream = con.getOutputStream();
    PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), true);

    writer.append("--" + boundary).append(CRLF);
    writer.append("Content-Disposition: form-data; name=\"" + "data" + "\"").append(CRLF);
    writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF);
    writer.append(CRLF);
    writer.append(bodytext).append(CRLF);
    writer.flush();

    writer.append(CRLF).flush();
    writer.append("--" + boundary + "--").append(CRLF);
    writer.close();
    int status = con.getResponseCode();
    if (status == HttpURLConnection.HTTP_OK) {
        StringBuilder sb = load(con);
        return sb;
    } else {
        throw new IOException("Server returned non-OK status: " + status);
    }
}

From source file:nl.denhaag.tw.comparators.gui.ReportWriter.java

public static void writeReport(File reportDir, String icon, String message, CompareResult compareResult,
        File oldWsdl, File newWsdl) throws IOException {
    FileUtils.deleteDirectory(reportDir);
    reportDir.mkdirs();//from ww  w . j a va  2  s  .  c om
    File layoutDir = new File(reportDir, "layout");
    layoutDir.mkdirs();
    String index = readFromClasspath("index.html");
    index = index.replaceAll("OLD_WSDL", oldWsdl.getCanonicalPath().replaceAll("\\\\", "/"));
    index = index.replaceAll("NEW_WSDL", newWsdl.getCanonicalPath().replaceAll("\\\\", "/"));
    index = index.replaceAll("RESULT_MESSAGE", message);
    index = index.replaceAll("RESULT_CLASS", icon);
    PrintWriter writer = new PrintWriter(new File(reportDir, "index.html"));
    writer.write(index);
    writer.flush();
    writer.close();
    copyFileFromClasspath("jquery.js", layoutDir);
    copyFileFromClasspath("jquery.cookie.js", layoutDir);
    copyFileFromClasspath("jquery-ui.custom.js", layoutDir);
    copyFileFromClasspath("jquery.dynatree.js", layoutDir);
    copyFileFromClasspath("ui.dynatree.css", layoutDir);
    copyFileFromClasspath("icons.gif", layoutDir);
    copyFileFromClasspath("loading.gif", layoutDir);
    copyFileFromClasspath("vline.gif", layoutDir);
    copyFileFromClasspath("invalid.png", layoutDir);
    copyFileFromClasspath("breaks.png", layoutDir);
    copyFileFromClasspath("warning.png", layoutDir);
    copyFileFromClasspath("ok.png", layoutDir);
    copyFileFromClasspath("default.css", layoutDir);
    PrintWriter printWriter = new PrintWriter(new File(reportDir, "report-data.json"));
    printWriter.append("[");
    write(printWriter, compareResult);
    printWriter.append("]");
    printWriter.flush();
    printWriter.close();
}

From source file:com.nridge.core.base.io.xml.IOXML.java

/**
 * Generates one or more space characters for indentation.
 *
 * @param aPW Print writer output stream.
 * @param aSpaceCount Count of spaces to indent.
 *//*from w  ww . j a va2 s.  c om*/
public static void indentLine(PrintWriter aPW, int aSpaceCount) {
    for (int i = 0; i < aSpaceCount; i++)
        aPW.append(StrUtl.CHAR_SPACE);
}

From source file:com.example.admin.processingboilerplate.JsonIO.java

public static JSONObject pushJson(String requestURL, String jsonDataName, JSONObject json) {
    try {// ww w.j a  va2  s . c o  m
        String boundary = "===" + System.currentTimeMillis() + "===";

        URL url = new URL(requestURL);
        //HttpURLConnection con = (HttpURLConnection) url.openConnection();
        URLConnection uc = (url).openConnection();
        HttpURLConnection con = requestURL.startsWith("https") ? (HttpsURLConnection) uc
                : (HttpURLConnection) uc;
        con.setUseCaches(false);
        con.setDoOutput(true);
        con.setDoInput(true);
        con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        con.setRequestProperty("User-Agent", USER_AGENT);
        OutputStream outputStream = con.getOutputStream();
        PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), true);

        writer.append("--" + boundary).append(CRLF);
        writer.append("Content-Disposition: form-data; name=\"" + "data" + "\"").append(CRLF);
        writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF);
        writer.append(CRLF);
        writer.append(json.toString()).append(CRLF);
        writer.flush();

        writer.append(CRLF).flush();
        writer.append("--" + boundary + "--").append(CRLF);
        writer.close();
        int status = con.getResponseCode();
        if (status == HttpURLConnection.HTTP_OK) {
            StringBuilder sb = load(con);
            try {
                json = new JSONObject(sb.toString());
                return json;
            } catch (JSONException e) {
                Log.e("loadJson", e.getMessage(), e);
                e.printStackTrace();
                return new JSONObject();
            }
        } else {
            throw new IOException("Server returned non-OK status: " + status);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return new JSONObject();
}

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)./* w  w w .  j av  a  2  s  .co  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();
    }
}