Example usage for java.io Writer close

List of usage examples for java.io Writer close

Introduction

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

Prototype

public abstract void close() throws IOException;

Source Link

Document

Closes the stream, flushing it first.

Usage

From source file:core.RESTCalls.RESTPost.java

public static String httpPost(String urlStr, String[] paramName, String[] paramVal) throws Exception {

    URL url = new URL(urlStr);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");

    conn.setDoOutput(true);//from  w ww.  ja  va2s  .co  m
    conn.setDoInput(true);
    conn.setUseCaches(false);
    conn.setAllowUserInteraction(false);
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    OutputStream out = conn.getOutputStream();

    Writer writer = new OutputStreamWriter(out, "UTF-8");

    for (int i = 0; i < paramName.length; i++) {

        writer.write(paramName[i]);
        writer.write("=");
        writer.write(URLEncoder.encode(paramVal[i], "UTF-8"));
        writer.write("&");
    }

    writer.close();
    out.close();

    if (conn.getResponseCode() != 200)
        throw new IOException(conn.getResponseMessage());

    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));

    StringBuilder sb = new StringBuilder();

    String line;

    while ((line = rd.readLine()) != null)
        sb.append(line + "\n");

    rd.close();

    conn.disconnect();

    return sb.toString();
}

From source file:com.swordlord.gozer.file.GozerFileLoader.java

public static String convertInputStreamToString(InputStream is) {
    String strReturn = "";

    if (is != null) {
        Writer writer = new StringWriter();

        char[] buffer = new char[1024];
        try {/*  w  w  w.  j a v a2s  .c om*/
            Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));

            int n;
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }

            reader.close();
            strReturn = writer.toString();
            writer.close();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

        }
    }

    return strReturn;
}

From source file:com.magic.util.FileUtil.java

public static void writeString(String path, String name, String s) throws IOException {
    Writer out = getBufferedWriter(path, name);

    try {//w ww .  ja  v a2  s  .c om
        out.write(s + System.getProperty("line.separator"));
    } catch (IOException e) {
        Debug.logError(e, module);
        throw e;
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                Debug.logError(e, module);
            }
        }
    }
}

From source file:org.jboss.as.test.integration.security.loginmodules.common.Utils.java

public static synchronized void logToFile(String what, String where) {
    try {/*from w  ww . ja  v a 2 s.  c om*/
        File file = new File(where);
        if (!file.exists()) {
            file.createNewFile();
        }
        OutputStream os = new FileOutputStream(file, true);
        Writer writer = new OutputStreamWriter(os);
        writer.write(what);
        if (!what.endsWith("\n")) {
            writer.write("\n");
        }
        writer.close();
        os.close();

    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:org.wso2.carbon.appmanager.integration.ui.Util.HttpUtil.java

public static HttpResponse doPut(URL endpoint, String postBody, Map<String, String> headers) throws Exception {
    HttpURLConnection urlConnection = null;
    try {//from  w w w  .j a  va2  s. com
        urlConnection = (HttpURLConnection) endpoint.openConnection();
        try {
            urlConnection.setRequestMethod("PUT");
        } catch (ProtocolException e) {
            throw new Exception("Shouldn't happen: HttpURLConnection doesn't support POST??", e);
        }
        urlConnection.setDoOutput(true);

        if (headers != null && headers.size() > 0) {
            Iterator<String> itr = headers.keySet().iterator();
            while (itr.hasNext()) {
                String key = itr.next();
                urlConnection.setRequestProperty(key, headers.get(key));
            }
        }
        OutputStream out = urlConnection.getOutputStream();
        try {
            Writer writer = new OutputStreamWriter(out, "UTF-8");
            writer.write(postBody);
            writer.close();
        } catch (IOException e) {
            throw new Exception("IOException while puting data", e);
        } finally {
            if (out != null) {
                out.close();
            }
        }

        // Get the response
        StringBuilder sb = new StringBuilder();
        BufferedReader rd = null;
        try {
            rd = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
        } catch (FileNotFoundException ignored) {
        } finally {
            if (rd != null) {
                rd.close();
            }
        }
        Iterator<String> itr = urlConnection.getHeaderFields().keySet().iterator();
        Map<String, String> responseHeaders = new HashMap();
        while (itr.hasNext()) {
            String key = itr.next();
            if (key != null) {
                responseHeaders.put(key, urlConnection.getHeaderField(key));
            }
        }
        return new HttpResponse(sb.toString(), urlConnection.getResponseCode(), responseHeaders);

    } catch (IOException e) {
        throw new Exception("Connection error (is server running at " + endpoint + " ?): " + e);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
}

From source file:com.nextep.designer.beng.model.impl.FileUtils.java

/**
 * Writes the specified contents to a file at the given file location.
 * /*from   w  w  w .jav  a 2  s .  co m*/
 * @param fileName name of the file to create (will be replaced if exists)
 * @param contents contents to write to the file.
 */
public static void writeToFile(String fileName, String contents) {
    // Retrieves the encoding specified in the preferences
    String encoding = SQLGenUtil.getPreference(PreferenceConstants.SQL_SCRIPT_ENCODING);
    final boolean convert = SQLGenUtil.getPreferenceBool(PreferenceConstants.SQL_SCRIPT_NEWLINE_CONVERT);
    if (convert) {
        String newline = CorePlugin.getService(IGenerationService.class).getNewLine();
        // Converting everything to \n then \n to expected new line
        contents = contents.replace("\r\n", "\n");
        contents = contents.replace("\r", "\n");
        contents = contents.replace("\n", newline);
    }
    Writer w = null;
    try {
        w = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(fileName)), encoding));
        w.write(contents);
    } catch (FileNotFoundException e) {
        throw new ErrorException(e);
    } catch (IOException e) {
        throw new ErrorException(e);
    } finally {
        if (w != null) {
            try {
                w.close();
            } catch (IOException e) {
                throw new ErrorException(e);
            }
        }
    }
}

From source file:edu.ku.brc.specify.tools.FixMetaTags.java

/**
* Change the contents of text file in its entirety, overwriting any
* existing text.//from w  w  w .  ja v  a 2 s.  c o m
*
* This style of implementation throws all exceptions to the caller.
*
* @param aFile is an existing file which can be written to.
* @throws IllegalArgumentException if param does not comply.
* @throws FileNotFoundException if the file does not exist.
* @throws IOException if problem encountered during write.
*/
static public void setContents(File aFile, String aContents) throws FileNotFoundException, IOException {
    if (aFile == null) {
        throw new IllegalArgumentException("File should not be null.");
    }
    if (!aFile.exists()) {
        throw new FileNotFoundException("File does not exist: " + aFile);
    }
    if (!aFile.isFile()) {
        throw new IllegalArgumentException("Should not be a directory: " + aFile);
    }
    if (!aFile.canWrite()) {
        throw new IllegalArgumentException("File cannot be written: " + aFile);
    }

    //declared here only to make visible to finally clause; generic reference
    Writer output = null;
    try {
        //use buffering
        //FileWriter always assumes default encoding is OK!
        output = new BufferedWriter(new FileWriter(aFile));
        output.write(aContents);
    } finally {
        //flush and close both "output" and its underlying FileWriter
        if (output != null)
            output.close();
    }
}

From source file:org.wso2.carbon.appmanager.integration.ui.Util.HttpUtil.java

public static HttpResponse doPost(URL endpoint, String postBody, Map<String, String> headers) throws Exception {
    HttpURLConnection urlConnection = null;
    try {/*from ww  w  .j a  v  a2  s. c o  m*/
        urlConnection = (HttpURLConnection) endpoint.openConnection();
        try {
            urlConnection.setRequestMethod("POST");
        } catch (ProtocolException e) {
            throw new Exception("Shouldn't happen: HttpURLConnection doesn't support POST??", e);
        }
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.setUseCaches(false);
        urlConnection.setAllowUserInteraction(false);

        // setting headers
        if (headers != null && headers.size() > 0) {
            Iterator<String> itr = headers.keySet().iterator();
            while (itr.hasNext()) {
                String key = itr.next();
                urlConnection.setRequestProperty(key, headers.get(key));
            }
        }

        OutputStream out = urlConnection.getOutputStream();
        try {
            Writer writer = new OutputStreamWriter(out, "UTF-8");
            writer.write(postBody);
            writer.close();
        } catch (IOException e) {
            throw new Exception("IOException while posting data", e);
        } finally {
            if (out != null) {
                out.close();
            }
        }

        // Get the response
        StringBuilder sb = new StringBuilder();
        BufferedReader rd = null;
        try {
            rd = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
        } catch (FileNotFoundException ignored) {
        } finally {
            if (rd != null) {
                rd.close();
            }
        }
        Iterator<String> itr = urlConnection.getHeaderFields().keySet().iterator();
        Map<String, String> responseHeaders = new HashMap();
        while (itr.hasNext()) {
            String key = itr.next();
            if (key != null) {
                responseHeaders.put(key, urlConnection.getHeaderField(key));
            }
        }
        return new HttpResponse(sb.toString(), urlConnection.getResponseCode(), responseHeaders);

    } catch (IOException e) {
        throw new Exception("Connection error (is server running at " + endpoint + " ?): " + e);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
}

From source file:com.ms.commons.test.classloader.util.CLFileUtil.java

public static void copyAndProcessFileContext(URL url, File newFile, String encoding, Processor processor) {
    try {//from w w w  .  j av a2s . c  om
        if (processor == null) {
            processor = DEFAULT_PROCESSOR;
        }

        if (!newFile.exists()) {
            String fileContext = readUrlToString(url, null);
            if (encoding == null) {
                if (FileUtil.convertURLToFilePath(url).endsWith(".xml") && fileContext.contains("\"UTF-8\"")) {
                    encoding = "UTF-8";
                    fileContext = readUrlToString(url, "UTF-8");
                }
            }

            (new File(getFilePath(newFile.getPath()))).mkdirs();

            Writer writer;
            if (encoding == null) {
                writer = new OutputStreamWriter(new FileOutputStream(newFile));
            } else {
                writer = new OutputStreamWriter(new FileOutputStream(newFile), encoding);
            }
            try {
                writer.write(processor.process(fileContext));
                writer.flush();
            } finally {
                writer.close();
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.dm.estore.common.utils.FileUtils.java

/**
 * Save text file from classpath to file.
 *
 * @param resource Classpath text resource
 * @param outputFile Output file/*from w  w  w  .  j  av  a  2  s .com*/
 * @param processor Optional line processor
 * @param encoding Text encoding
 * @throws IOException Exception
 */
public static void saveTextFileFromClassPath(String resource, String outputFile, String encoding,
        TextStreamProcessor processor) throws IOException {

    final InputStream inputStream = FileUtils.class.getResourceAsStream(resource);
    final Scanner scanner = new Scanner(inputStream, encoding);
    final Writer out = new OutputStreamWriter(new FileOutputStream(outputFile), encoding);
    try {

        while (scanner.hasNextLine()) {
            final String nextLine = scanner.nextLine();
            out.write(processor != null ? processor.process(nextLine) : nextLine);
            out.write(NEW_LINE_SEP);
        }

    } finally {
        out.close();
        scanner.close();
    }

}