Example usage for java.io BufferedWriter BufferedWriter

List of usage examples for java.io BufferedWriter BufferedWriter

Introduction

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

Prototype

public BufferedWriter(Writer out) 

Source Link

Document

Creates a buffered character-output stream that uses a default-sized output buffer.

Usage

From source file:Main.java

/**
 * Writes out the contents.//from  w  w  w  .  j  a  v a2 s . com
 * @param outFile outFile
 * @param contents contents
 * @throws FileNotFoundException FileNotFoundException
 * @throws IOException IOException
 */
public static void setContents(final File outFile, final String contents)
        throws FileNotFoundException, IOException {
    if (outFile == null) {
        throw new IllegalArgumentException("File should not be null."); //$NON-NLS-1$
    }
    if (outFile.exists()) {
        if (!outFile.isFile()) {
            throw new IllegalArgumentException("Should not be a directory: " + outFile); //$NON-NLS-1$
        }
        if (!outFile.canWrite()) {
            throw new IllegalArgumentException("File cannot be written: " + outFile); //$NON-NLS-1$
        }
    }

    Writer output = null;
    try {
        output = new BufferedWriter(new FileWriter(outFile));
        if (contents != null) {
            output.write(contents);
            output.flush();
        }

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

From source file:com.amalto.core.storage.record.DataRecordDefaultWriter.java

public void write(DataRecord record, OutputStream output) throws IOException {
    Writer out = new BufferedWriter(new OutputStreamWriter(output, "UTF-8")); //$NON-NLS-1$
    write(record, out);// w  w  w  .j ava  2  s  .  c o  m
}

From source file:it.unibas.spicy.persistence.idgenerator.utils.ExportCsv.java

public void performAction() {
    //        CSVWriter csvWriter;
    BufferedWriter bwriter;/*from w w  w. ja  va  2  s  .  co m*/
    try {
        bwriter = new BufferedWriter(new FileWriter(FilenameUtils.separatorsToSystem(pathToExport)));
        //            csvWriter = new CSVWriter(new FileWriter(FilenameUtils.separatorsToSystem(pathToExport)), CSVWriter.DEFAULT_SEPARATOR, CSVWriter.DEFAULT_QUOTE_CHARACTER, CSVWriter.NO_ESCAPE_CHARACTER);
        //            csvWriter.writeNext(header, false);
        int line = 1;
        String str = "";
        for (int i = 0; i < header.length; i++) {
            str += "\"" + header[i].trim() + "\",";
        }
        str = str.substring(0, str.length() - 1);
        str += "\n";
        for (InputDataModel output : targetValues) {
            String row = "";
            for (String s : output.getValue()) {
                if (s != null)
                    row += "\"" + s + "\",";
                else
                    row += ",";
                //                    row = row.replace("\"", "");
            }
            //                csvWriter.writeNext(row.substring(0, row.length()-1).split(","),false);
            row = row.substring(0, row.length() - 1);
            str += row + "\n";
        }
        bwriter.write(str);
        bwriter.close();
        //            csvWriter.close();
    } catch (IOException e) {
        System.err.println(e.getMessage());
        System.exit(-1);
    }

}

From source file:Main.java

/**
 * Transforms an xml-file (xmlFilename) using an xsl-file (xslFilename) and
 * writes the output into file (outputFilename).
 * //from  w ww .  j  av  a2  s . c  o  m
 * @param xmlFile
 *            File: the xml-source-file to be transformed
 * @param xslFile
 *            File: the xsl-file with the transformation rules
 * @param outputFilename
 *            String: the name of the file the result will be written to
 */
public static void applyXSL(File xmlFile, File xslFile, String outputFilename) {
    try {
        // DocumentBuilderFactory docBFactory = DocumentBuilderFactory
        // .newInstance();
        // DocumentBuilder docBuilder = docBFactory.newDocumentBuilder();
        StreamSource xslStream = new StreamSource(xslFile);
        TransformerFactory transFactory = TransformerFactory.newInstance();
        Transformer transformer = transFactory.newTransformer(xslStream);
        StreamSource xmlStream = new StreamSource(xmlFile);
        StreamResult result = new StreamResult(new BufferedWriter(new FileWriter(outputFilename)));
        transformer.transform(xmlStream, result);
        result.getWriter().close();
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

From source file:manager.GameElement.java

public static void save() throws IOException {
    BufferedWriter bw = new BufferedWriter(new FileWriter("scores.json"));
    bw.write(toJSON().toJSONString());//from   ww w  .ja va2 s .  c  o m
    bw.flush();
}

From source file:com.athena.peacock.common.core.util.SshExecUtil.java

/**
 * <pre>/* w w  w  . ja  v a 2 s  .co  m*/
 * 
 * </pre>
 * @param targetHost
 * @param commandList
 * @throws IOException 
 */
public static void executeCommand(TargetHost targetHost, List<String> commandList) throws IOException {
    fstream = new FileWriter(output, false);
    out = new BufferedWriter(fstream);

    for (String command : commandList) {
        out.write("[" + targetHost.getUsername() + "@" + targetHost.getHost() + " ~]$ " + command + "\n");
        out.write(executeCommand(targetHost, command));
    }

    IOUtils.closeQuietly(out);
}

From source file:com.cws.esolutions.security.main.PasswordUtility.java

public static void main(final String[] args) {
    final String methodName = PasswordUtility.CNAME + "#main(final String[] args)";

    if (DEBUG) {//w  ww  .  j ava2 s . c o  m
        DEBUGGER.debug("Value: {}", methodName);
    }

    if (args.length == 0) {
        HelpFormatter usage = new HelpFormatter();
        usage.printHelp(PasswordUtility.CNAME, options, true);

        System.exit(1);
    }

    BufferedReader bReader = null;
    BufferedWriter bWriter = null;

    try {
        // load service config first !!
        SecurityServiceInitializer.initializeService(PasswordUtility.SEC_CONFIG, PasswordUtility.LOG_CONFIG,
                false);

        if (DEBUG) {
            DEBUGGER.debug("Options options: {}", options);

            for (String arg : args) {
                DEBUGGER.debug("Value: {}", arg);
            }
        }

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

        if (DEBUG) {
            DEBUGGER.debug("CommandLineParser parser: {}", parser);
            DEBUGGER.debug("CommandLine commandLine: {}", commandLine);
            DEBUGGER.debug("CommandLine commandLine.getOptions(): {}", (Object[]) commandLine.getOptions());
            DEBUGGER.debug("CommandLine commandLine.getArgList(): {}", commandLine.getArgList());
        }

        final SecurityConfigurationData secConfigData = PasswordUtility.svcBean.getConfigData();
        final SecurityConfig secConfig = secConfigData.getSecurityConfig();
        final PasswordRepositoryConfig repoConfig = secConfigData.getPasswordRepo();
        final SystemConfig systemConfig = secConfigData.getSystemConfig();

        if (DEBUG) {
            DEBUGGER.debug("SecurityConfigurationData secConfig: {}", secConfigData);
            DEBUGGER.debug("SecurityConfig secConfig: {}", secConfig);
            DEBUGGER.debug("RepositoryConfig secConfig: {}", repoConfig);
            DEBUGGER.debug("SystemConfig systemConfig: {}", systemConfig);
        }

        if (commandLine.hasOption("encrypt")) {
            if ((StringUtils.isBlank(repoConfig.getPasswordFile()))
                    || (StringUtils.isBlank(repoConfig.getSaltFile()))) {
                System.err.println("The password/salt files are not configured. Entries will not be stored!");
            }

            File passwordFile = FileUtils.getFile(repoConfig.getPasswordFile());
            File saltFile = FileUtils.getFile(repoConfig.getSaltFile());

            if (DEBUG) {
                DEBUGGER.debug("File passwordFile: {}", passwordFile);
                DEBUGGER.debug("File saltFile: {}", saltFile);
            }

            final String entryName = commandLine.getOptionValue("entry");
            final String username = commandLine.getOptionValue("username");
            final String password = commandLine.getOptionValue("password");
            final String salt = RandomStringUtils.randomAlphanumeric(secConfig.getSaltLength());

            if (DEBUG) {
                DEBUGGER.debug("String entryName: {}", entryName);
                DEBUGGER.debug("String username: {}", username);
                DEBUGGER.debug("String password: {}", password);
                DEBUGGER.debug("String salt: {}", salt);
            }

            final String encodedSalt = PasswordUtils.base64Encode(salt);
            final String encodedUserName = PasswordUtils.base64Encode(username);
            final String encryptedPassword = PasswordUtils.encryptText(password, salt,
                    secConfig.getSecretAlgorithm(), secConfig.getIterations(), secConfig.getKeyBits(),
                    secConfig.getEncryptionAlgorithm(), secConfig.getEncryptionInstance(),
                    systemConfig.getEncoding());
            final String encodedPassword = PasswordUtils.base64Encode(encryptedPassword);

            if (DEBUG) {
                DEBUGGER.debug("String encodedSalt: {}", encodedSalt);
                DEBUGGER.debug("String encodedUserName: {}", encodedUserName);
                DEBUGGER.debug("String encodedPassword: {}", encodedPassword);
            }

            if (commandLine.hasOption("store")) {
                try {
                    new File(passwordFile.getParent()).mkdirs();
                    new File(saltFile.getParent()).mkdirs();

                    boolean saltFileExists = (saltFile.exists()) ? true : saltFile.createNewFile();

                    if (DEBUG) {
                        DEBUGGER.debug("saltFileExists: {}", saltFileExists);
                    }

                    // write the salt out first
                    if (!(saltFileExists)) {
                        throw new IOException("Unable to create salt file");
                    }

                    boolean passwordFileExists = (passwordFile.exists()) ? true : passwordFile.createNewFile();

                    if (!(passwordFileExists)) {
                        throw new IOException("Unable to create password file");
                    }

                    if (commandLine.hasOption("replace")) {
                        File[] files = new File[] { saltFile, passwordFile };

                        if (DEBUG) {
                            DEBUGGER.debug("File[] files: {}", (Object) files);
                        }

                        for (File file : files) {
                            if (DEBUG) {
                                DEBUGGER.debug("File: {}", file);
                            }

                            String currentLine = null;
                            File tmpFile = new File(FileUtils.getTempDirectory() + "/" + "tmpFile");

                            if (DEBUG) {
                                DEBUGGER.debug("File tmpFile: {}", tmpFile);
                            }

                            bReader = new BufferedReader(new FileReader(file));
                            bWriter = new BufferedWriter(new FileWriter(tmpFile));

                            while ((currentLine = bReader.readLine()) != null) {
                                if (!(StringUtils.equals(currentLine.trim().split(",")[0], entryName))) {
                                    bWriter.write(currentLine + System.getProperty("line.separator"));
                                    bWriter.flush();
                                }
                            }

                            bWriter.close();

                            FileUtils.deleteQuietly(file);
                            FileUtils.copyFile(tmpFile, file);
                            FileUtils.deleteQuietly(tmpFile);
                        }
                    }

                    FileUtils.writeStringToFile(saltFile, entryName + "," + encodedUserName + "," + encodedSalt
                            + System.getProperty("line.separator"), true);
                    FileUtils.writeStringToFile(passwordFile, entryName + "," + encodedUserName + ","
                            + encodedPassword + System.getProperty("line.separator"), true);
                } catch (IOException iox) {
                    ERROR_RECORDER.error(iox.getMessage(), iox);
                }
            }

            System.out.println("Entry Name " + entryName + " stored.");
        }

        if (commandLine.hasOption("decrypt")) {
            String saltEntryName = null;
            String saltEntryValue = null;
            String decryptedPassword = null;
            String passwordEntryName = null;

            if ((StringUtils.isEmpty(commandLine.getOptionValue("entry"))
                    && (StringUtils.isEmpty(commandLine.getOptionValue("username"))))) {
                throw new ParseException("No entry or username was provided to decrypt.");
            }

            if (StringUtils.isEmpty(commandLine.getOptionValue("username"))) {
                throw new ParseException("no entry provided to decrypt");
            }

            String entryName = commandLine.getOptionValue("entry");
            String username = commandLine.getOptionValue("username");

            if (DEBUG) {
                DEBUGGER.debug("String entryName: {}", entryName);
                DEBUGGER.debug("String username: {}", username);
            }

            File passwordFile = FileUtils.getFile(repoConfig.getPasswordFile());
            File saltFile = FileUtils.getFile(repoConfig.getSaltFile());

            if (DEBUG) {
                DEBUGGER.debug("File passwordFile: {}", passwordFile);
                DEBUGGER.debug("File saltFile: {}", saltFile);
            }

            if ((!(saltFile.canRead())) || (!(passwordFile.canRead()))) {
                throw new IOException(
                        "Unable to read configured password/salt file. Please check configuration and/or permissions.");
            }

            for (String lineEntry : FileUtils.readLines(saltFile, systemConfig.getEncoding())) {
                saltEntryName = lineEntry.split(",")[0];

                if (DEBUG) {
                    DEBUGGER.debug("String saltEntryName: {}", saltEntryName);
                }

                if (StringUtils.equals(saltEntryName, entryName)) {
                    saltEntryValue = PasswordUtils.base64Decode(lineEntry.split(",")[2]);

                    break;
                }
            }

            if (StringUtils.isEmpty(saltEntryValue)) {
                throw new SecurityException("No entries were found that matched the provided information");
            }

            for (String lineEntry : FileUtils.readLines(passwordFile, systemConfig.getEncoding())) {
                passwordEntryName = lineEntry.split(",")[0];

                if (DEBUG) {
                    DEBUGGER.debug("String passwordEntryName: {}", passwordEntryName);
                }

                if (StringUtils.equals(passwordEntryName, saltEntryName)) {
                    String decodedPassword = PasswordUtils.base64Decode(lineEntry.split(",")[2]);

                    decryptedPassword = PasswordUtils.decryptText(decodedPassword, saltEntryValue,
                            secConfig.getSecretAlgorithm(), secConfig.getIterations(), secConfig.getKeyBits(),
                            secConfig.getEncryptionAlgorithm(), secConfig.getEncryptionInstance(),
                            systemConfig.getEncoding());

                    break;
                }
            }

            if (StringUtils.isEmpty(decryptedPassword)) {
                throw new SecurityException("No entries were found that matched the provided information");
            }

            System.out.println(decryptedPassword);
        } else if (commandLine.hasOption("encode")) {
            System.out.println(PasswordUtils.base64Encode((String) commandLine.getArgList().get(0)));
        } else if (commandLine.hasOption("decode")) {
            System.out.println(PasswordUtils.base64Decode((String) commandLine.getArgList().get(0)));
        }
    } catch (IOException iox) {
        ERROR_RECORDER.error(iox.getMessage(), iox);

        System.err.println("An error occurred during processing: " + iox.getMessage());
        System.exit(1);
    } catch (ParseException px) {
        ERROR_RECORDER.error(px.getMessage(), px);

        System.err.println("An error occurred during processing: " + px.getMessage());
        System.exit(1);
    } catch (SecurityException sx) {
        ERROR_RECORDER.error(sx.getMessage(), sx);

        System.err.println("An error occurred during processing: " + sx.getMessage());
        System.exit(1);
    } catch (SecurityServiceException ssx) {
        ERROR_RECORDER.error(ssx.getMessage(), ssx);
        System.exit(1);
    } finally {
        try {
            if (bReader != null) {
                bReader.close();
            }

            if (bWriter != null) {
                bReader.close();
            }
        } catch (IOException iox) {
        }
    }

    System.exit(0);
}

From source file:com.oozierunner.core.FileManager.java

public static BufferedWriter getFileWriter(String fileName) throws IOException {

    System.out.println("File to write in :-> " + fileName);

    File file = new File(fileName);

    // if file doesnt exists, then create it
    if (!file.exists()) {
        file.createNewFile();/*from ww w  .  j a  v  a 2s. co m*/
    }

    FileWriter fileWriter = new FileWriter(file.getAbsoluteFile());
    BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

    return bufferedWriter;
}

From source file:core.Web.java

public static String httpRequest(URL url, Map<String, String> properties, JSONObject message) {
    //        System.out.println(url);
    try {// w  w w.j a v a2s  .  c om
        // Create connection
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        //connection.addRequestProperty("Authorization", API_KEY);
        // Set properties if needed
        if (properties != null && !properties.isEmpty()) {
            properties.forEach(connection::setRequestProperty);
        }
        // Post message
        if (message != null) {
            // Maybe somewhere
            connection.setDoOutput(true);
            //                connection.setRequestProperty("Accept", "application/json");
            try (BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(connection.getOutputStream()))) {
                writer.write(message.toString());
            }
        }
        // Establish connection
        connection.connect();
        int responseCode = connection.getResponseCode();

        if (responseCode != 200) {
            System.err.println("Error " + responseCode + ":" + url);
            return null;
        }

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
            String line;
            String content = "";
            while ((line = reader.readLine()) != null) {
                content += line;
            }
            return content;
        }

    } catch (IOException ex) {
        Logger.getLogger(Web.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:juicebox.tools.utils.juicer.apa.APAUtils.java

/**
 * @param filename//from   w ww  .jav a2 s .c  om
 * @param matrix
 */
public static void saveMeasures(String filename, RealMatrix matrix) {

    Writer writer = null;

    APARegionStatistics apaStats = new APARegionStatistics(matrix);

    try {
        writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename), "utf-8"));
        writer.write("P2M" + '\t' + apaStats.getPeak2mean() + '\n');
        writer.write("P2UL" + '\t' + apaStats.getPeak2UL() + '\n');
        writer.write("P2UR" + '\t' + apaStats.getPeak2UR() + '\n');
        writer.write("P2LL" + '\t' + apaStats.getPeak2LL() + '\n');
        writer.write("P2LR" + '\t' + apaStats.getPeak2LR() + '\n');
        writer.write("ZscoreLL" + '\t' + apaStats.getZscoreLL());
    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        try {
            if (writer != null)
                writer.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}