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:mobile.tiis.appv2.helpers.Utils.java

public static void writeNetworkLogFileOnSD(String sBody) {
    try {//ww  w  . j a v a 2s  . c  o  m
        File root = new File(Environment.getExternalStorageDirectory(), "TIIS");
        if (!root.exists()) {
            root.mkdirs();
        }
        File gpxfile = new File(root, "network_log_file.txt");

        PrintWriter fileStream = new PrintWriter(new FileOutputStream(gpxfile, true));
        fileStream.append(System.getProperty("line.separator"));
        fileStream.append(sBody);
        fileStream.flush();
        fileStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:io.apiman.tools.i18n.TemplateScanner.java

/**
 * Output the sorted map of strings to the specified output file.
 * @param strings/*from   ww  w  .ja v  a 2s. c  o  m*/
 * @param outputFile
 * @throws FileNotFoundException
 */
private static void outputMessages(TreeMap<String, String> strings, File outputFile)
        throws FileNotFoundException {
    PrintWriter writer = new PrintWriter(new FileOutputStream(outputFile));
    for (Entry<String, String> entry : strings.entrySet()) {
        String key = entry.getKey();
        String val = entry.getValue();
        writer.append(key);
        writer.append('=');
        writer.append(val);
        writer.append("\n");
    }
    writer.flush();
    writer.close();
}

From source file:org.wso2.mb.integration.common.clients.operations.utils.AndesClientUtils.java

public static void createTestFileToSend(String filePathToRead, String filePathToCreate, int sizeInKB) {
    String sampleKB10StringToWrite = "";
    BufferedReader br = null;// w  w  w  .ja  va  2 s  .  co  m
    try {
        br = new BufferedReader(new FileReader(filePathToRead));
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();

        while (line != null) {
            sb.append(line);
            sb.append('\n');
            line = br.readLine();
        }
        sampleKB10StringToWrite = sb.toString();
    } catch (FileNotFoundException e) {
        log.error("File to read sample string to create text file to send is not found", e);
    } catch (IOException e) {
        log.error("Error in reading sample file to create text file to send", e);
    } finally {

        try {
            if (br != null) {
                br.close();
            }
        } catch (IOException e) {
            log.error("Error while closing buffered reader", e);
        }

    }
    try {

        File fileToCreate = new File(filePathToCreate);

        //no need to recreate if exists
        if (fileToCreate.exists()) {
            log.info("File requested to create already exists. Skipping file creation... " + filePathToCreate);
            return;
        } else {
            boolean createFileSuccess = fileToCreate.createNewFile();
            if (createFileSuccess) {
                log.info("Successfully created a file to append content for sending at " + filePathToCreate);
            }
        }

        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filePathToCreate));
        PrintWriter printWriter = new PrintWriter(bufferedWriter);

        for (int count = 0; count < sizeInKB / 10; count++) {
            printWriter.append(sampleKB10StringToWrite);
        }

    } catch (IOException e) {
        log.error("Error. File to print received messages is not provided", e);
    }

}

From source file:org.transitime.applications.RmiQuery.java

/**
 * Displays the command line options on stdout
 * //from w  w  w  .ja va  2s . c o m
 * @param options Command line options to be displayed
 */
private static void displayCommandLineOptionsAndExit(Options options) {
    // Display help
    final String commandLineSyntax = "java transitime.jar";
    final PrintWriter writer = new PrintWriter(System.out);
    writer.append("A command line application that allows user to request data\n"
            + "from the server. Such information includes predictions and\n" + "vehicles.\n\n");
    final HelpFormatter helpFormatter = new HelpFormatter();
    helpFormatter.printHelp(writer, 80, // printedRowWidth
            commandLineSyntax, "args:", // header
            options, 2, // spacesBeforeOption
            2, // spacesBeforeOptionDescription
            null, // footer
            true); // displayUsage
    writer.close();
    System.exit(0);
}

From source file:org.caleydo.data.importer.tcga.FirehoseProvider.java

private static File parseMAF(File maf) {

    File out = new File(maf.getParentFile(), "P" + maf.getName());
    if (out.exists())
        return out;
    log.fine(maf.getAbsolutePath() + " parsing maf file");
    final String TAB = "\t";

    try (BufferedReader reader = Files.newBufferedReader(maf.toPath(), Charset.forName("UTF-8"))) {
        List<String> header = Arrays.asList(reader.readLine().split(TAB));
        int geneIndex = header.indexOf("Hugo_Symbol");
        int sampleIndex = header.indexOf("Tumor_Sample_Barcode");
        // gene x sample x mutated
        Table<String, String, Boolean> mutated = TreeBasedTable.create();
        String line = null;//w w  w.j  a  v  a 2  s  . c  o  m
        while ((line = reader.readLine()) != null) {
            String[] columns = line.split(TAB);
            mutated.put(columns[geneIndex], columns[sampleIndex], Boolean.TRUE);
        }

        File tmp = new File(out.getParentFile(), out.getName() + ".tmp");
        PrintWriter w = new PrintWriter(tmp);
        w.append("Hugo_Symbol");
        List<String> cols = new ArrayList<>(mutated.columnKeySet());
        for (String sample : cols) {
            w.append(TAB).append(sample);
        }
        w.println();
        Set<String> rows = mutated.rowKeySet();
        for (String gene : rows) {
            w.append(gene);
            for (String sample : cols) {
                w.append(TAB).append(mutated.contains(gene, sample) ? '1' : '0');
            }
            w.println();
        }
        w.close();
        Files.move(tmp.toPath(), out.toPath(), StandardCopyOption.REPLACE_EXISTING);

        log.fine(maf.getAbsolutePath() + " parsed maf file stats: " + mutated.size() + " " + rows.size() + " "
                + cols.size());
        return out;
    } catch (IOException e) {
        log.log(Level.SEVERE, maf.getAbsolutePath() + " maf parsing error: " + e.getMessage(), e);
    }
    return null;
}

From source file:org.neo4j.consistency.checking.full.ExecutionOrderIntegrationTest.java

private static void assertSameChecks(Map<String, Throwable> singlePassChecks,
        Map<String, Throwable> multiPassChecks) {
    if (!singlePassChecks.keySet().equals(multiPassChecks.keySet())) {
        Map<String, Throwable> missing = new HashMap<>(singlePassChecks);
        Map<String, Throwable> extras = new HashMap<>(multiPassChecks);
        missing.keySet().removeAll(multiPassChecks.keySet());
        extras.keySet().removeAll(singlePassChecks.keySet());

        StringBuilder headers = new StringBuilder("\n");
        StringWriter diff = new StringWriter();
        PrintWriter writer = new PrintWriter(diff);
        if (!missing.isEmpty()) {
            writer.append("These expected checks were missing:\n");
            for (Map.Entry<String, Throwable> check : missing.entrySet()) {
                writer.append("  ");
                headers.append("Missing: ").append(check.getKey()).append("\n");
                check.getValue().printStackTrace(writer);
            }/*from   w ww . j a  v  a2 s  .c o  m*/
        }
        if (!extras.isEmpty()) {
            writer.append("These extra checks were not expected:\n");
            for (Map.Entry<String, Throwable> check : extras.entrySet()) {
                writer.append("  ");
                headers.append("Unexpected: ").append(check.getKey()).append("\n");
                check.getValue().printStackTrace(writer);
            }
        }
        fail(headers.toString() + diff.toString());
    }
}

From source file:org.kalypso.model.hydrology.internal.preprocessing.NAControlConverter.java

private static void writeResultInformation(final NaModell naModel, final Node rootNode,
        final IDManager idManager, final PrintWriter writer) {
    final IFeatureBindingCollection<Node> nodes = naModel.getNodes();
    for (final Node node : nodes) {
        if (rootNode != null && rootNode.equals(node)) {
            // fuer root node immer ein ergebnis generieren
            writer.append(idManager.getAsciiID(node) + "\n"); //$NON-NLS-1$
        } else if (rootNode == null && node.isGenerateResults()) {
            // fuer nicht root node nur ergebnisse generieren wenn gewuenscht
            writer.append(idManager.getAsciiID(node) + "\n"); //$NON-NLS-1$
        }//from   w  w w .j a va2s  . com
    }

    writer.append("99999\n"); //$NON-NLS-1$
    // teilgebiete
    final IFeatureBindingCollection<Catchment> catchments = naModel.getCatchments();
    for (final Catchment catchment : catchments) {
        if (catchment.isGenerateResults())
            writer.append(idManager.getAsciiID(catchment) + "\n"); //$NON-NLS-1$
    }
    writer.append("99999\n"); //$NON-NLS-1$
}

From source file:org.kalypso.model.hydrology.internal.preprocessing.NAControlConverter.java

private static void writeInitialDates(final NAModellControl controlFE, final PrintWriter writer) {
    final DateFormat format = NATimeSettings.getInstance().getLzsLzgDateFormat();

    final Date[] initialDates = controlFE.getInitialDatesToBeWritten();
    for (final Date iniDate : initialDates) {
        final String iniString = format.format(iniDate);
        writer.append(iniString + "\n"); //$NON-NLS-1$
    }//from w  w w  . ja v  a2s.  c  o m
    writer.append("99999\n"); //$NON-NLS-1$
}

From source file:org.structr.web.auth.HttpAuthenticator.java

public static void writeContent(String content, HttpServletResponse response) throws IOException {

    try {/* www .  j  a  v  a 2  s  .com*/

        response.setStatus(HttpServletResponse.SC_OK);
        response.setCharacterEncoding("UTF-8");

        PrintWriter writer = response.getWriter();
        writer.append(content);
        writer.flush();
        writer.close();

    } catch (IllegalStateException ise) {

        logger.log(Level.WARNING, "Could not write to output stream", ise.getMessage());

    }

}

From source file:com.android.volley.toolbox.http.HurlStack.java

/**
 * Perform a multipart request on a connection
 *
 * @param connection The Connection to perform the multi part request
 * @param request    param additionalHeaders
 *                   param multipartParams
 *                   The params to add to the Multi Part request
 *                   param filesToUpload
 *                   The files to upload
 * @throws ProtocolException/*  ww w.j  a  va 2s .  co  m*/
 */
private static void setConnectionParametersForMultipartRequest(HttpURLConnection connection, Request<?> request)
        throws IOException, ProtocolException {

    Map<String, File> filesToUpload = request.getFilesToUpload();
    if (filesToUpload != null) {
        for (String key : filesToUpload.keySet()) {
            File file = filesToUpload.get(key);

            if (file == null || !file.exists()) {
                throw new IOException(String.format("File not found: %s", file.getAbsolutePath()));
            }
            if (file.isDirectory()) {
                throw new IOException(String.format("File is a directory: %s", file.getAbsolutePath()));
            }
        }
    }

    final int curTime = (int) (System.currentTimeMillis() / 1000);
    final String boundary = BOUNDARY_PREFIX + curTime;
    StringBuilder sb = new StringBuilder();
    Map<String, MultiPartParam> multipartParams = request.getMultiPartParams();
    for (String key : multipartParams.keySet()) {
        MultiPartParam param = multipartParams.get(key);

        sb.append(boundary).append(CRLF)
                .append(String.format(HEADER_CONTENT_DISPOSITION + COLON_SPACE + FORM_DATA, key)).append(CRLF)
                .append(HEADER_CONTENT_TYPE + COLON_SPACE).append(param.contentType).append(CRLF).append(CRLF)
                .append(param.value).append(CRLF);
    }
    final String charset = request.getParamsEncoding();
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);
    connection.setRequestProperty(HEADER_CONTENT_TYPE, String.format(CONTENT_TYPE_MULTIPART, charset, curTime));
    //        connection.setChunkedStreamingMode(0);

    PrintWriter writer = null;
    try {
        OutputStream out = connection.getOutputStream();
        writer = new PrintWriter(new OutputStreamWriter(out, charset), true);

        writer.append(sb).flush();

        for (String key : filesToUpload.keySet()) {

            File file = filesToUpload.get(key);

            writer.append(boundary).append(CRLF)
                    .append(String.format(
                            HEADER_CONTENT_DISPOSITION + COLON_SPACE + FORM_DATA + SEMICOLON_SPACE + FILENAME,
                            key, file.getName()))
                    .append(CRLF).append(HEADER_CONTENT_TYPE + COLON_SPACE + CONTENT_TYPE_OCTET_STREAM)
                    .append(CRLF).append(HEADER_CONTENT_TRANSFER_ENCODING + COLON_SPACE + BINARY).append(CRLF)
                    .append(CRLF).flush();

            BufferedInputStream input = null;
            try {
                input = new BufferedInputStream(new FileInputStream(file));
                int bufferLength = 0;

                byte[] buffer = new byte[1024];
                while ((bufferLength = input.read(buffer)) > 0) {
                    out.write(buffer, 0, bufferLength);
                }
                out.flush(); // Important! Output cannot be closed. Close of
                // writer will close
                // output as well.
            } finally {
                if (input != null)
                    try {
                        input.close();
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
            }
            writer.append(CRLF).flush(); // CRLF is important! It indicates
            // end of binary
            // boundary.
        }

        // End of multipart/form-data.
        writer.append(boundary).append(BOUNDARY_PREFIX).append(CRLF).flush();

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

    } finally {
        if (writer != null) {
            writer.close();
        }
    }
}