Example usage for java.io BufferedWriter close

List of usage examples for java.io BufferedWriter close

Introduction

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

Prototype

@SuppressWarnings("try")
    public void close() throws IOException 

Source Link

Usage

From source file:com.trackplus.ddl.DataReader.java

private static void writeInfoToFile(Map<String, String> info, String fileName) throws DDLException {
    BufferedWriter writer = createBufferedWriter(fileName);
    Iterator<String> it = info.keySet().iterator();
    while (it.hasNext()) {
        String key = it.next();//from   w w w.j av a 2  s. co m
        String value = info.get(key);
        try {
            writer.write(key);
            writer.write("=");
            writer.write(value);
            writer.newLine();
        } catch (IOException ex) {
            throw new DDLException(ex.getMessage(), ex);
        }
    }

    try {
        writer.flush();
        writer.close();
    } catch (IOException e) {
        LOGGER.error("Error on close stream file " + fileName + " :" + e.getMessage());
        throw new DDLException(e.getMessage(), e);
    }
}

From source file:com.tesora.dve.common.PEFileUtils.java

/**
 * Write the text out to the specified filename.
 * //w w  w.  j  ava2s. com
 * @param fileName
 * @param text
 * @param overwriteContents
 * @throws Exception
 */
public static void writeToFile(File file, String text, boolean overwriteContents) throws PEException {
    BufferedWriter bw = null;
    try {
        if (file.exists() && !overwriteContents)
            throw new PEException("File '" + file.getCanonicalPath() + "' already exists");

        createDirectory(file.getParent());

        bw = new BufferedWriter(new FileWriter(file));
        bw.write(text);
    } catch (Exception e) {
        throw new PEException("Failed to write to file", e);
    } finally {
        if (bw != null) {
            try {
                bw.close();
            } catch (Exception e) {
                // Eat it
            }
        }
    }
}

From source file:com.ing.connector.util.WStringUtil.java

public static void appendFile(String source, String filetoappend) {

    try {/*w  ww  .j  a v a2s  .c  o m*/
        boolean append = true;
        File filesrc = new File(source);
        BufferedWriter output = new BufferedWriter(new FileWriter(filesrc, append));

        File ftoappend = new File(filetoappend);
        BufferedReader br = new BufferedReader(new FileReader(ftoappend));
        String line = br.readLine();

        while (line != null) {
            output.write(line);
            output.newLine();
            line = br.readLine();
        }
        output.close();
        br.close();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:de.tudarmstadt.ukp.dkpro.tc.mallet.util.MalletUtils.java

public static void writeFeatureValuesToFile(String featureValues[], String outcome, File outputFile)
        throws IOException {
    BufferedWriter bw = new BufferedWriter(
            new OutputStreamWriter(new GZIPOutputStream(new FileOutputStream(outputFile, true)), "UTF-8"));
    bw.write("\n");
    for (String featureValue : featureValues) {
        bw.write(featureValue + " ");
    }/*from www  . ja v a2 s . co  m*/
    bw.write(outcome);
    bw.flush();
    bw.close();
}

From source file:com.photon.phresco.impl.IPhoneApplicationProcessor.java

public static void updateJsonInfo(JSONObject toJson, String jsonFile) throws PhrescoException {
    BufferedWriter out = null;
    FileWriter fstream = null;//from   w  w w .j  a  v  a  2  s .com
    try {
        Gson gson = new Gson();
        FileWriter writer = null;
        String json = gson.toJson(toJson);
        writer = new FileWriter(jsonFile);
        writer.write(json);
        writer.flush();
    } catch (IOException e) {
        throw new PhrescoException(e);
    } finally {
        try {
            if (out != null) {
                out.close();
            }
            if (fstream != null) {
                fstream.close();
            }
        } catch (IOException e) {
            throw new PhrescoException(e);
        }
    }
}

From source file:com.echopf.ECHOQuery.java

/**
 * Sends a HTTP request with optional request contents/parameters.
 * @param path a request url path//from   w  w w.ja v  a2s.c om
 * @param httpMethod a request method (GET/POST/PUT/DELETE)
 * @param data request contents/parameters
 * @param multipart use multipart/form-data to encode the contents
 * @throws ECHOException
 */
public static InputStream requestRaw(String path, String httpMethod, JSONObject data, boolean multipart)
        throws ECHOException {
    final String secureDomain = ECHO.secureDomain;
    if (secureDomain == null)
        throw new IllegalStateException("The SDK is not initialized.Please call `ECHO.initialize()`.");

    String baseUrl = new StringBuilder("https://").append(secureDomain).toString();
    String url = new StringBuilder(baseUrl).append("/").append(path).toString();

    HttpsURLConnection httpClient = null;

    try {
        URL urlObj = new URL(url);

        StringBuilder apiUrl = new StringBuilder(baseUrl).append(urlObj.getPath()).append("/rest_api=1.0/");

        // Append the QueryString contained in path
        boolean isContainQuery = urlObj.getQuery() != null;
        if (isContainQuery)
            apiUrl.append("?").append(urlObj.getQuery());

        // Append the QueryString from data
        if (httpMethod.equals("GET") && data != null) {
            boolean firstItem = true;
            Iterator<?> iter = data.keys();
            while (iter.hasNext()) {
                if (firstItem && !isContainQuery) {
                    firstItem = false;
                    apiUrl.append("?");
                } else {
                    apiUrl.append("&");
                }
                String key = (String) iter.next();
                String value = data.optString(key);
                apiUrl.append(key);
                apiUrl.append("=");
                apiUrl.append(value);
            }
        }

        URL urlConn = new URL(apiUrl.toString());
        httpClient = (HttpsURLConnection) urlConn.openConnection();
    } catch (IOException e) {
        throw new ECHOException(e);
    }

    final String appId = ECHO.appId;
    final String appKey = ECHO.appKey;
    final String accessToken = ECHO.accessToken;

    if (appId == null || appKey == null)
        throw new IllegalStateException("The SDK is not initialized.Please call `ECHO.initialize()`.");

    InputStream responseInputStream = null;

    try {
        httpClient.setRequestMethod(httpMethod);
        httpClient.addRequestProperty("X-ECHO-APP-ID", appId);
        httpClient.addRequestProperty("X-ECHO-APP-KEY", appKey);

        // Set access token
        if (accessToken != null && !accessToken.isEmpty())
            httpClient.addRequestProperty("X-ECHO-ACCESS-TOKEN", accessToken);

        // Build content
        if (!httpMethod.equals("GET") && data != null) {

            httpClient.setDoOutput(true);
            httpClient.setChunkedStreamingMode(0); // use default chunk size

            if (multipart == false) { // application/json

                httpClient.addRequestProperty("CONTENT-TYPE", "application/json");
                BufferedWriter wrBuffer = new BufferedWriter(
                        new OutputStreamWriter(httpClient.getOutputStream()));
                wrBuffer.write(data.toString());
                wrBuffer.close();

            } else { // multipart/form-data

                final String boundary = "*****" + UUID.randomUUID().toString() + "*****";
                final String twoHyphens = "--";
                final String lineEnd = "\r\n";
                final int maxBufferSize = 1024 * 1024 * 3;

                httpClient.setRequestMethod("POST");
                httpClient.addRequestProperty("CONTENT-TYPE", "multipart/form-data; boundary=" + boundary);

                final DataOutputStream outputStream = new DataOutputStream(httpClient.getOutputStream());

                try {

                    JSONObject postData = new JSONObject();
                    postData.putOpt("method", httpMethod);
                    postData.putOpt("data", data);

                    new Object() {

                        public void post(JSONObject data, List<String> currentKeys)
                                throws JSONException, IOException {

                            Iterator<?> keys = data.keys();
                            while (keys.hasNext()) {
                                String key = (String) keys.next();
                                List<String> newKeys = new ArrayList<String>(currentKeys);
                                newKeys.add(key);

                                Object val = data.get(key);

                                // convert JSONArray into JSONObject
                                if (val instanceof JSONArray) {
                                    JSONArray array = (JSONArray) val;
                                    JSONObject val2 = new JSONObject();

                                    for (Integer i = 0; i < array.length(); i++) {
                                        val2.putOpt(i.toString(), array.get(i));
                                    }

                                    val = val2;
                                }

                                // build form-data name
                                String name = "";
                                for (int i = 0; i < newKeys.size(); i++) {
                                    String key2 = newKeys.get(i);
                                    name += (i == 0) ? key2 : "[" + key2 + "]";
                                }

                                if (val instanceof ECHOFile) {

                                    ECHOFile file = (ECHOFile) val;
                                    if (file.getLocalBytes() == null)
                                        continue;

                                    InputStream fileInputStream = new ByteArrayInputStream(
                                            file.getLocalBytes());

                                    if (fileInputStream != null) {

                                        String mimeType = URLConnection
                                                .guessContentTypeFromName(file.getFileName());

                                        // write header
                                        outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                                        outputStream.writeBytes("Content-Disposition: form-data; name=\"" + name
                                                + "\"; filename=\"" + file.getFileName() + "\"" + lineEnd);
                                        outputStream.writeBytes("Content-Type: " + mimeType + lineEnd);
                                        outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
                                        outputStream.writeBytes(lineEnd);

                                        // write content
                                        int bytesAvailable, bufferSize, bytesRead;
                                        do {
                                            bytesAvailable = fileInputStream.available();
                                            bufferSize = Math.min(bytesAvailable, maxBufferSize);
                                            byte[] buffer = new byte[bufferSize];
                                            bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                                            if (bytesRead <= 0)
                                                break;
                                            outputStream.write(buffer, 0, bufferSize);
                                        } while (true);

                                        fileInputStream.close();
                                        outputStream.writeBytes(lineEnd);
                                    }

                                } else if (val instanceof JSONObject) {

                                    this.post((JSONObject) val, newKeys);

                                } else {

                                    String data2 = null;
                                    try { // in case of boolean
                                        boolean bool = data.getBoolean(key);
                                        data2 = bool ? "true" : "";
                                    } catch (JSONException e) { // if the value is not a Boolean or the String "true" or "false".
                                        data2 = val.toString().trim();
                                    }

                                    // write header
                                    outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                                    outputStream.writeBytes(
                                            "Content-Disposition: form-data; name=\"" + name + "\"" + lineEnd);
                                    outputStream
                                            .writeBytes("Content-Type: text/plain; charset=UTF-8" + lineEnd);
                                    outputStream.writeBytes("Content-Length: " + data2.length() + lineEnd);
                                    outputStream.writeBytes(lineEnd);

                                    // write content
                                    byte[] bytes = data2.getBytes();
                                    for (int i = 0; i < bytes.length; i++) {
                                        outputStream.writeByte(bytes[i]);
                                    }

                                    outputStream.writeBytes(lineEnd);
                                }

                            }
                        }
                    }.post(postData, new ArrayList<String>());

                } catch (JSONException e) {

                    throw new ECHOException(e);

                } finally {

                    outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                    outputStream.flush();
                    outputStream.close();

                }
            }

        } else {

            httpClient.addRequestProperty("CONTENT-TYPE", "application/json");

        }

        if (httpClient.getResponseCode() != -1 /*== HttpURLConnection.HTTP_OK*/) {
            responseInputStream = httpClient.getInputStream();
        }

    } catch (IOException e) {

        // get http response code
        int errorCode = -1;

        try {
            errorCode = httpClient.getResponseCode();
        } catch (IOException e1) {
            throw new ECHOException(e1);
        }

        // get error contents
        JSONObject responseObj;
        try {
            String jsonStr = ECHOQuery.getResponseString(httpClient.getErrorStream());
            responseObj = new JSONObject(jsonStr);
        } catch (JSONException e1) {
            if (errorCode == 404) {
                throw new ECHOException(ECHOException.RESOURCE_NOT_FOUND, "Resource not found.");
            }

            throw new ECHOException(ECHOException.INVALID_JSON_FORMAT, "Invalid JSON format.");
        }

        //
        if (responseObj != null) {
            int code = responseObj.optInt("error_code");
            String message = responseObj.optString("error_message");

            if (code != 0 || !message.equals("")) {
                JSONObject details = responseObj.optJSONObject("error_details");
                if (details == null) {
                    throw new ECHOException(code, message);
                } else {
                    throw new ECHOException(code, message, details);
                }
            }
        }

        throw new ECHOException(e);

    }

    return responseInputStream;
}

From source file:com.twinsoft.convertigo.engine.util.ProjectUtils.java

public static void makeReplacementsInFile(List<Replacement> replacements, String filePath) throws Exception {
    File file = new File(filePath);
    if (file.exists()) {
        String line;//from ww  w .j  a  v  a  2 s .c o m
        StringBuffer sb = new StringBuffer();

        BufferedReader br = new BufferedReader(new FileReader(filePath));
        while ((line = br.readLine()) != null) {
            for (Replacement replacement : replacements) {
                String lineBegin = replacement.getStartsWith();
                if ((lineBegin == null) || (line.trim().startsWith(lineBegin))) {
                    line = line.replaceAll(replacement.getSource(), replacement.getTarget());
                }
            }
            sb.append(line + "\n");
        }
        br.close();

        BufferedWriter out = new BufferedWriter(new FileWriter(filePath));
        out.write(sb.toString());
        out.close();
    } else {
        throw new Exception("File \"" + filePath + "\" does not exist");
    }
}

From source file:mase.MaseEvolve.java

public static File writeConfig(String[] args, Map<String, String> params, File outDir,
        boolean replaceDirWildcard) throws IOException {
    File configFile = File.createTempFile("maseconfig", ".params");

    // Write the parameter map into a new file
    BufferedWriter bw = new BufferedWriter(new FileWriter(configFile));

    // Write the command line arguments in a comment
    bw.write("#");
    for (String arg : args) {
        bw.write(" " + arg);
    }//from w  w  w.  j a va  2 s  .  c om
    bw.newLine();

    // Write the parameters correctly padded
    int maxLen = -1;
    for (String str : params.keySet()) {
        maxLen = Math.max(maxLen, str.length());
    }

    for (Entry<String, String> e : params.entrySet()) {
        String value = e.getValue();
        if (value.contains("$") && replaceDirWildcard) {
            File f = new File(outDir, value.replace("$", ""));
            value = f.getAbsolutePath().replace("\\", "/");
        }
        bw.write(StringUtils.rightPad(e.getKey(), maxLen) + " = " + value);
        bw.newLine();
    }
    bw.close();

    return configFile;
}

From source file:com.dtolabs.rundeck.ExpandRunServer.java

/**
 * Copy from file to toFile, expanding properties in the contents
 *
 * @param inputStream  input stream// ww  w  .j a  v a 2 s  . c o  m
 * @param outputStream output stream
 * @param props        properties
 */
private static void expandTemplate(final InputStream inputStream, final OutputStream outputStream,
        final Properties props) throws IOException {

    final BufferedReader read = new BufferedReader(new InputStreamReader(inputStream));
    final BufferedWriter write = new BufferedWriter(new OutputStreamWriter(outputStream));
    String line = read.readLine();
    while (null != line) {
        write.write(expandProperties(props, line));
        write.write(LINESEP);
        line = read.readLine();
    }
    write.flush();
    write.close();
    read.close();
}

From source file:com.netflix.lipstick.Main.java

public static boolean dryrun(String scriptFile, PigContext pigContext)
        throws RecognitionException, IOException {
    BufferedReader rd = new BufferedReader(new FileReader(scriptFile));

    DryRunGruntParser dryrun = new DryRunGruntParser(rd, scriptFile, pigContext);

    boolean hasMacro = dryrun.parseStopOnError();

    if (hasMacro) {
        String expandedFile = scriptFile.replace(".substituted", ".expanded");
        BufferedWriter fw = new BufferedWriter(new FileWriter(expandedFile));
        fw.append(dryrun.getResult());/*from  w ww  . j  a  va 2  s .c  o m*/
        fw.close();
    }
    return hasMacro;
}