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:it.unibas.spicybenchmark.persistence.DAOLogFile.java

public static void saveLog(String log, String logFile) throws DAOException {
    BufferedWriter writer = null;
    try {//from   www  .j  av  a 2 s .c  om
        File f = new File(logFile);
        f.getParentFile().mkdirs();
        FileWriter fileWriter = new FileWriter(logFile);
        writer = new BufferedWriter(fileWriter);
        writer.write(log);
    } catch (FileNotFoundException fnfe) {
        throw new DAOException(" File not found: " + fnfe);
    } catch (IOException ioe) {
        throw new DAOException(" Error: " + ioe);
    } catch (NoSuchElementException nse) {
        throw new DAOException(" Error in file format: " + nse);
    } finally {
        try {
            if (writer != null) {
                writer.close();
            }
        } catch (IOException ioe) {
        }
    }
}

From source file:it.geosolutions.tools.io.file.writer.Writer.java

/**
 * Open 'destination' file in append mode and append content of the
 * 'toAppend' file/* ww  w.ja  v  a  2 s.  c  o m*/
 * 
 * @param toAppend
 * @param destination
 * @throws IOException
 */
public static void appendFile(File toAppend, File destination) throws IOException {
    FileWriter fw = null;
    BufferedWriter bw = null;
    LineIterator it = null;
    try {
        fw = new FileWriter(destination, true);
        bw = new BufferedWriter(fw);
        it = FileUtils.lineIterator(toAppend);
        while (it.hasNext()) {
            bw.append(it.nextLine());
            bw.newLine();
        }
        bw.flush();
    } finally {
        if (it != null) {
            it.close();
        }
        if (bw != null) {
            IOUtils.closeQuietly(bw);
        }
        if (fw != null) {
            IOUtils.closeQuietly(fw);
        }
    }
}

From source file:edu.cmu.lti.oaqa.knn4qa.apps.ParsedPost.java

public static void main(String args[]) {

    Options options = new Options();

    options.addOption(INPUT_PARAM, null, true, INPUT_DESC);
    options.addOption(OUTPUT_PARAM, null, true, OUTPUT_DESC);
    options.addOption(CommonParams.MAX_NUM_REC_PARAM, null, true, CommonParams.MAX_NUM_REC_DESC);
    options.addOption(DEBUG_PRINT_PARAM, null, false, DEBUG_PRINT_DESC);
    options.addOption(EXCLUDE_CODE_PARAM, null, false, EXCLUDE_CODE_DESC);

    CommandLineParser parser = new org.apache.commons.cli.GnuParser();

    HashMap<String, ParsedPost> hQuestions = new HashMap<String, ParsedPost>();

    try {/*w ww  . j  a v  a2 s  . com*/
        CommandLine cmd = parser.parse(options, args);

        String inputFile = cmd.getOptionValue(INPUT_PARAM);

        if (null == inputFile)
            Usage("Specify: " + INPUT_PARAM, options);

        String outputFile = cmd.getOptionValue(OUTPUT_PARAM);

        if (null == outputFile)
            Usage("Specify: " + OUTPUT_PARAM, options);

        InputStream input = CompressUtils.createInputStream(inputFile);
        BufferedWriter output = new BufferedWriter(new FileWriter(new File(outputFile)));

        int maxNumRec = Integer.MAX_VALUE;

        String tmp = cmd.getOptionValue(CommonParams.MAX_NUM_REC_PARAM);

        if (tmp != null)
            maxNumRec = Integer.parseInt(tmp);

        boolean debug = cmd.hasOption(DEBUG_PRINT_PARAM);

        boolean excludeCode = cmd.hasOption(EXCLUDE_CODE_PARAM);

        System.out.println("Processing at most " + maxNumRec + " records, excluding code? " + excludeCode);

        XmlIterator xi = new XmlIterator(input, ROOT_POST_TAG);

        String elem;

        output.write("<?xml version='1.0' encoding='UTF-8'?><ystfeed>\n");

        for (int num = 1; num <= maxNumRec && !(elem = xi.readNext()).isEmpty(); ++num) {
            ParsedPost post = null;
            try {
                post = parsePost(elem, excludeCode);

                if (!post.mAcceptedAnswerId.isEmpty()) {
                    hQuestions.put(post.mId, post);
                } else if (post.mpostIdType.equals("2")) {
                    String parentId = post.mParentId;
                    String id = post.mId;
                    if (!parentId.isEmpty()) {
                        ParsedPost parentPost = hQuestions.get(parentId);
                        if (parentPost != null && parentPost.mAcceptedAnswerId.equals(id)) {
                            output.write(createYahooAnswersQuestion(parentPost, post));
                            hQuestions.remove(parentId);
                        }
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
                throw new Exception("Error parsing record # " + num + ", error message: " + e);
            }
            if (debug) {
                System.out.println(String.format("%s parentId=%s acceptedAnswerId=%s type=%s", post.mId,
                        post.mParentId, post.mAcceptedAnswerId, post.mpostIdType));
                System.out.println("================================");
                if (!post.mTitle.isEmpty()) {
                    System.out.println(post.mTitle);
                    System.out.println("--------------------------------");
                }
                System.out.println(post.mBody);
                System.out.println("================================");
            }
        }

        output.write("</ystfeed>\n");

        input.close();
        output.close();

    } catch (ParseException e) {
        Usage("Cannot parse arguments", options);
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println("Terminating due to an exception: " + e);
        System.exit(1);
    }

}

From source file:com.netflix.config.DynamicFileConfigurationTest.java

static File createConfigFile(String prefix) throws Exception {
    configFile = File.createTempFile(prefix, ".properties");
    BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(new FileOutputStream(configFile), "UTF-8"));
    writer.write("dprops1=123456789");
    writer.newLine();/*from w  w  w .j  av a  2s .  c  o  m*/
    writer.write("dprops2=79.98");
    writer.newLine();
    writer.close();
    System.err.println(configFile.getPath() + " created");
    return configFile;
}

From source file:mrdshinse.sql2xlsx.util.FileUtil.java

public static File create(File file, String str) {
    try (PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file)))) {
        pw.print(str);//from w  ww.  j  a  v  a 2  s  .  c  om
    } catch (IOException ex) {
        return file;
    }
    return file;
}

From source file:com.raphfrk.craftproxyclient.json.JSONManager.java

public static byte[] JSONToBytes(JSONObject obj) {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    OutputStreamWriter wos = new OutputStreamWriter(bos, StandardCharsets.UTF_8);
    BufferedWriter br = new BufferedWriter(wos);
    try {/*from w ww.j ava 2 s  .  com*/
        obj.writeJSONString(br);
        br.close();
    } catch (IOException e) {
        return null;
    }
    return bos.toByteArray();
}

From source file:com.siemens.sw360.exporter.CSVExport.java

@NotNull
private static ByteArrayOutputStream getCSVOutputStream(Iterable<String> csvHeaderIterable,
        Iterable<Iterable<String>> inputIterable) throws IOException {
    final ByteArrayOutputStream outB = new ByteArrayOutputStream();
    try (Writer out = new BufferedWriter(new OutputStreamWriter(outB));) {
        CSVPrinter csvPrinter = new CSVPrinter(out, CommonUtils.sw360CsvFormat);
        csvPrinter.printRecord(csvHeaderIterable);
        csvPrinter.printRecords(inputIterable);
        csvPrinter.flush();/*from   w  w w  .j  a v  a 2 s  .c o  m*/
        csvPrinter.close();
    } catch (Exception e) {
        outB.close();
        throw e;
    }

    return outB;

}

From source file:com.devdungeon.httpexamples.DownloadFile.java

private static void download(String url, String filepath) {
    HttpClient client = new DefaultHttpClient();

    HttpParams params = client.getParams();
    HttpConnectionParams.setConnectionTimeout(params, 1000 * 5);
    HttpConnectionParams.setSoTimeout(params, 1000 * 5);

    HttpGet request = new HttpGet(url);

    HttpResponse response = null;// ww w.ja va 2  s  .  co m
    try {
        response = client.execute(request);
    } catch (IOException ex) {
        Logger.getLogger(HttpGetExample.class.getName()).log(Level.SEVERE, null, ex);
    }
    BufferedReader rd;
    String line = null;
    try {
        rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        FileWriter fileWriter = new FileWriter(filepath);
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
        while ((line = rd.readLine()) != null) {
            bufferedWriter.write(line);
            bufferedWriter.newLine();
        }
        bufferedWriter.close();

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

From source file:gov.nih.nci.restgen.util.GeneratorUtil.java

public static void writeFile(String _outputDir, String _fileName, String _content) {
    BufferedWriter bufferedWriter = null;

    try {//from www  . j  a  v  a2  s .c  om
        createOutputDir(_outputDir);
        File file = new File(_outputDir, _fileName);
        FileWriter fileWriter = new FileWriter(file);
        bufferedWriter = new BufferedWriter(fileWriter);
        bufferedWriter.write(_content);
        bufferedWriter.flush();
    } catch (Throwable t) {
        throw new RuntimeException(t);
    } finally {
        if (bufferedWriter != null) {
            try {
                bufferedWriter.close();
            } catch (Throwable t) {
            }
        }
    }
}

From source file:com.daphne.es.maintain.staticresource.web.controller.utils.YuiCompressorUtils.java

/**
 * js/css  ??.min.js/css//from  ww  w . j  ava 2  s  .  c o  m
 * @param fileName
 * @return ??
 */
public static String compress(final String fileName) {
    String minFileName = null;
    final String extension = FilenameUtils.getExtension(fileName);
    if ("js".equalsIgnoreCase(extension)) {
        minFileName = fileName.substring(0, fileName.length() - 3) + ".min.js";
    } else if ("css".equals(extension)) {
        minFileName = fileName.substring(0, fileName.length() - 4) + ".min.css";
    } else {
        throw new RuntimeException(
                "file type only is js/css, but was fileName:" + fileName + ", extension:" + extension);
    }
    Reader in = null;
    Writer out = null;
    try {
        in = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), Constants.ENCODING));
        out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(minFileName), Constants.ENCODING));

        if ("js".equals(extension)) {

            CustomErrorReporter errorReporter = new CustomErrorReporter();

            JavaScriptCompressor compressor = new JavaScriptCompressor(in, errorReporter);
            compressor.compress(out, 10, true, false, false, false);

            if (errorReporter.hasError()) {
                throw new RuntimeException(errorReporter.getErrorMessage());
            }

        } else if ("css".equals(extension)) {

            CssCompressor compressor = new CssCompressor(in);
            compressor.compress(out, 10);
        }
    } catch (Exception e) {
        //?js/css
        try {
            FileUtils.copyFile(new File(fileName), new File(minFileName));
        } catch (IOException ioException) {
            throw new RuntimeException("compress error:" + ioException.getMessage(), ioException);
        }
        throw new RuntimeException("compress error:" + e.getMessage(), e);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
            }
        }
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
            }
        }
    }

    if (FileUtils.sizeOf(new File(minFileName)) == 0) {
        try {
            FileUtils.copyFile(new File(fileName), new File(minFileName));
        } catch (IOException ioException) {
            throw new RuntimeException("compress error:" + ioException.getMessage(), ioException);
        }
    }

    return minFileName;
}