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:com.pimp.companionforband.utils.jsontocsv.writer.CSVWriter.java

private void writeToFile(String output, String fileName) throws FileNotFoundException {
    BufferedWriter writer = null;
    try {//from  www .  java2s.co m
        writer = new BufferedWriter(new FileWriter(fileName));
        writer.write(output);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        close(writer);
    }
}

From source file:cc.redpen.formatter.JSONFormatter.java

@Override
public void format(PrintWriter pw, Map<Document, List<ValidationError>> docErrorsMap)
        throws RedPenException, IOException {
    BufferedWriter writer = new BufferedWriter(new PrintWriter(pw));
    JSONArray errors = new JSONArray();
    docErrorsMap.forEach((doc, errorList) -> errors.put(asJSON(doc, errorList)));
    writer.write(errors.toString());/*from ww  w.jav  a  2s . c o m*/
    writer.flush();
}

From source file:com.yifanlu.PSXperiaTool.StringReplacement.java

public void replaceStringsIn(File file) throws IOException {
    String name = file.getPath();
    BufferedReader reader = new BufferedReader(new FileReader(file));
    BufferedWriter writer = new BufferedWriter(new FileWriter(name + ".tmp"));
    Logger.debug("Writing to temporary file: %s", name + ".tmp");
    String line;/*  w  w  w  . j  a v a  2s  . com*/
    while ((line = reader.readLine()) != null) {
        Logger.verbose("Data line before replacement: %s", line);
        Iterator<String> keys = mMap.keySet().iterator();
        while (keys.hasNext()) {
            String key = keys.next();
            String value = mMap.get(key);
            line = line.replaceAll(key, value);
        }
        Logger.verbose("Data line after replacement: %s", line);
        writer.write(line);
        writer.newLine();
    }
    reader.close();
    writer.close();
    file.delete();
    FileUtils.moveFile(new File(name + ".tmp"), file);
    Logger.debug("Successfully cleaned up and done with string replacement.");
}

From source file:is.brendan.WarpMarkers.WarpMarkersTimerTask.java

public void run() {
    JSONArray jsonList = plugin.getJSON();
    JSONArray jsonListUpdates = plugin.getUpdatesJSON();

    if (jsonList != null) {
        try {//from  w w  w  .j  ava2  s .c o  m
            PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(outputFile)));
            writer.print(jsonList);
            writer.close();
        } catch (java.io.IOException e) {
            plugin.log(Level.SEVERE, "Unable to write to " + outputFile + ": " + e.getMessage(), e);
            e.printStackTrace();
        }
    }
    if (jsonListUpdates != null) {
        try {
            PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(updateFile)));
            writer.print(jsonListUpdates);
            writer.close();
        } catch (java.io.IOException e) {
            plugin.log(Level.SEVERE, "Unable to write to " + updateFile + ": " + e.getMessage(), e);
            e.printStackTrace();
        }
    }
}

From source file:localSPs.CubbyAPI.java

public void createNewLogin(String folder) {
    String accessToken = folder;/*from w  ww .  j  av a  2  s  . c  om*/
    BufferedWriter output = null;
    try {
        File file = new File("SPsCredentials/CubbyLogin.txt");
        output = new BufferedWriter(new FileWriter(file));
        output.write(accessToken);
        output.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:com.idiro.utils.db.mysql.MySqlUtils.java

public static boolean changeFormatAfterExport(File in, File out, char delimiter, Collection<String> header,
        Collection<String> quotes) {
    //We expect that in is a csv file and out a file
    boolean ok = true;
    FileChecker fChIn = new FileChecker(in), fChOut = new FileChecker(out);

    if (!fChIn.isFile()) {
        logger.error(fChIn.getFilename() + " is not a directory or does not exist");
        return false;
    }/*from w  w  w.j  ava2 s.c  o m*/

    if (fChOut.exists()) {
        if (fChOut.isDirectory()) {
            logger.error(fChOut.getFilename() + " is a directory");
            return false;
        }
        logger.warn(fChOut.getFilename() + " already exists, it will be removed");
        String out_str = out.getAbsolutePath();
        out.delete();
        out = new File(out_str);
    }

    BufferedWriter bw = null;
    BufferedReader br = null;

    try {
        bw = new BufferedWriter(new FileWriter(out));

        logger.debug("read the file" + in.getAbsolutePath());
        br = new BufferedReader(new FileReader(in));
        String strLine;
        if (header != null && !header.isEmpty()) {
            Iterator<String> it = header.iterator();
            String headerLine = it.next();
            while (it.hasNext()) {
                headerLine += delimiter + it.next();
            }
            bw.write(headerLine + "\n");
        }

        //Read File Line By Line
        while ((strLine = br.readLine()) != null) {
            bw.write(DataFileUtils.addQuotesToLine(
                    DataFileUtils.getCleanLine(strLine.replace(',', delimiter), delimiter, delimiter), quotes,
                    delimiter) + "\n");
        }
        br.close();

        bw.close();
    } catch (FileNotFoundException e1) {
        logger.error(e1.getCause() + " " + e1.getMessage());
        logger.error("Fail to read " + in.getAbsolutePath());
        ok = false;
    } catch (IOException e1) {
        logger.error("Error writting, reading on the filesystem from the directory" + fChIn.getFilename()
                + " to the file " + fChOut.getFilename());
        ok = false;
    }
    if (ok) {
        in.delete();
    }
    return ok;
}

From source file:foam.dao.HTTPSink.java

@Override
public void put(Object obj, Detachable sub) {
    HttpURLConnection conn = null;
    OutputStream os = null;/* ww  w . j  av  a  2s  .  co m*/
    BufferedWriter writer = null;

    try {
        Outputter outputter = null;
        conn = (HttpURLConnection) new URL(url_).openConnection();
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);
        if (format_ == Format.JSON) {
            outputter = new foam.lib.json.Outputter(OutputterMode.NETWORK);
            conn.addRequestProperty("Accept", "application/json");
            conn.addRequestProperty("Content-Type", "application/json");
        } else if (format_ == Format.XML) {
            // TODO: make XML Outputter
            conn.addRequestProperty("Accept", "application/xml");
            conn.addRequestProperty("Content-Type", "application/xml");
        }
        conn.connect();

        os = conn.getOutputStream();
        writer = new BufferedWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8));
        writer.write(outputter.stringify((FObject) obj));
        writer.flush();
        writer.close();
        os.close();

        // check response code
        int code = conn.getResponseCode();
        if (code != HttpServletResponse.SC_OK) {
            throw new RuntimeException("Http server did not return 200.");
        }
    } catch (Throwable t) {
        throw new RuntimeException(t);
    } finally {
        IOUtils.closeQuietly(writer);
        IOUtils.closeQuietly(os);
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:heigit.ors.util.FileUtility.java

public static void writeFile(String fileName, String encoding, String content) throws IOException {
    Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), encoding));
    out.append(content);/*  w w  w.j a v  a2 s.  c o  m*/
    out.flush();
    out.close();
}

From source file:bioLockJ.util.MetadataUtil.java

/**
 * When a new column is added to metadata, this method will add the column, with all row values.
 * The updated file is output to the "outputDir" to be picked up by the next executor.
 * @param name/*from   w  w  w.  j  a va 2 s . c  o  m*/
 * @param map
 * @param fileDir
 * @throws Exception
 */
public static void addNumericColumn(final String name, final Map<String, Integer> map, final File fileDir)
        throws Exception {
    if (getAttributeNames().contains(name)) {
        Log.out.warn("Metadata already contains column [" + name + "] so this data will not be added to "
                + metadataFile.getName());
        return;
    }

    numericFields.add(name);

    final BufferedReader reader = new BufferedReader(new FileReader(metadataFile));
    metadataFile = new File(fileDir.getAbsolutePath() + File.separator + metadataFile.getName());
    final BufferedWriter writer = new BufferedWriter(new FileWriter(metadataFile));

    Log.out.info("Adding new attribute [" + name + "] to metadata");
    boolean isHeaderRow = true;
    try {
        final Set<String> keys = map.keySet();
        for (String line = reader.readLine(); line != null; line = reader.readLine()) {
            final StringTokenizer st = new StringTokenizer(line, Constants.TAB_DELIM);
            if (isHeaderRow) {
                isHeaderRow = false;
                line += Constants.TAB_DELIM + name;
            } else {
                final String id = st.nextToken();
                if (keys.contains(id)) {
                    line += Constants.TAB_DELIM + map.get(id);
                } else {
                    line += Constants.TAB_DELIM + Config.requireString(Config.INPUT_NULL_VALUE);
                }
            }

            writer.write(line + Constants.RETURN);
        }
    } catch (final Exception ex) {
        Log.out.error("Error occurred updating metadata with new attribute [" + name + "]", ex);
    } finally {
        reader.close();
        writer.close();
        refresh();
    }
}

From source file:localSPs.BearDataShareAPI.java

public void createNewLogin(String folder) {
    String accessToken = folder;// w  w  w . j av a2 s. co m
    BufferedWriter output = null;
    try {
        File file = new File("SPsCredentials/BearDataShareLogin.txt");
        output = new BufferedWriter(new FileWriter(file));
        output.write(accessToken);
        output.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}