Example usage for java.io FileWriter close

List of usage examples for java.io FileWriter close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Usage

From source file:ca.uvic.cs.tagsea.wizards.TagNetworkSender.java

public static synchronized void send(String xml, IProgressMonitor sendMonitor, int id)
        throws InvocationTargetException {
    sendMonitor.beginTask("Uploading Tags", 100);
    sendMonitor.subTask("Saving Temporary file...");
    File location = TagSEAPlugin.getDefault().getStateLocation().toFile();
    File temp = new File(location, "tagsea.temp.file.txt");
    if (temp.exists()) {
        String message = "Unable to send tags. Unable to create temporary file.";
        IOException ex = new IOException(message);
        throw (new InvocationTargetException(ex, message));
    }/*from  www.j a v a 2  s  .c  om*/
    try {
        FileWriter writer = new FileWriter(temp);
        writer.write(xml);
        writer.flush();
        writer.close();
    } catch (IOException e) {
        throw new InvocationTargetException(e);
    }
    sendMonitor.worked(5);
    sendMonitor.subTask("Uploading Tags...");
    String uploadScript = "http://stgild.cs.uvic.ca/cgi-bin/tagSEAUpload.cgi";
    PostMethod post = new PostMethod(uploadScript);

    String fileName = getToday() + ".txt";
    try {
        Part[] parts = { new StringPart("KIND", "tag"), new FilePart("MYLAR" + id, fileName, temp) };
        post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
        HttpClient client = new HttpClient();
        int status = client.executeMethod(post);
        String resp = getData(post.getResponseBodyAsStream());
        if (status != 200) {
            IOException ex = new IOException(resp);
            throw (ex);
        }
    } catch (IOException e) {
        throw new InvocationTargetException(e, e.getLocalizedMessage());
    } finally {
        sendMonitor.worked(90);
        sendMonitor.subTask("Deleting Temporary File");
        temp.delete();
        sendMonitor.done();
    }

}

From source file:net.chunkyhosting.Roe.CHGManagerLauncher.utils.JSON.java

public static void writeJsonToFile(JSONObject json, File file) throws IOException {

    FileWriter writer = new FileWriter(file.toString());

    try {/*from  w w  w . j  av  a 2s. c  om*/

        writer.write(json.toString(4));

    } finally {

        writer.flush();
        writer.close();

    }

}

From source file:edu.isi.karma.util.FileUtil.java

public static void writePrettyPrintedJSONObjectToFile(JSONObject json, File jsonFile)
        throws JSONException, IOException {
    String prettyPrintedJSONString = json.toString(4);
    FileWriter writer = new FileWriter(jsonFile);
    writer.write(prettyPrintedJSONString);
    writer.close();
    logger.debug("Done writing JSON Object into a File: " + jsonFile.getAbsolutePath());
}

From source file:com.ratebeer.android.gui.components.helpers.ImportExport.java

/**
 * Export the offline ratings from the database to a file
 * @param list The offline ratings to export
 * @param outputfile The file to write to
 * @throws JSONException Thrown when the content could not be written to JSON
 * @throws IOException Thrown when the file could not be written to
 *//*from  www.  j ava  2s  .  co  m*/
public static void exportRatings(List<OfflineRating> list, File outputfile) throws JSONException, IOException {

    // Create a single JSON object with all offline ratings
    JSONObject json = new JSONObject();
    JSONArray ratings = new JSONArray();

    for (OfflineRating item : list) {
        JSONObject rating = new JSONObject();
        rating.put("beerId", item.getBeerId());
        rating.put("beerName", item.getBeerName());
        rating.put("originalRatingId", item.getOriginalRatingId());
        rating.put("originalRatingDate", item.getOriginalRatingDate());
        rating.put("aroma", item.getAroma());
        rating.put("appearance", item.getAppearance());
        rating.put("taste", item.getTaste());
        rating.put("palate", item.getPalate());
        rating.put("overall", item.getOverall());
        rating.put("comments", item.getComments());
        rating.put("timeSaved", item.getTimeSaved().getTime());
        ratings.put(rating);
    }
    json.put("ratings", ratings);

    // Serialize the JSON object to a file
    if (outputfile.exists()) {
        outputfile.delete();
    }
    outputfile.getParentFile().mkdirs();
    outputfile.createNewFile();
    FileWriter writer = new FileWriter(outputfile);
    writer.write(json.toString(2));
    writer.flush();
    writer.close();

}

From source file:Main.java

/**
 * write file// w w w  .j  a va  2  s .  c o m
 *
 * @param filePath
 * @param content
 * @param append
 *            is append, if true, write to the end of file, else clear content of file and write into it
 * @return return true
 * @throws IOException
 *             if an error occurs while operator FileWriter
 */
public static boolean writeFile(String filePath, String content, boolean append) {
    FileWriter fileWriter = null;
    try {
        fileWriter = new FileWriter(filePath, append);
        fileWriter.write(content);
        fileWriter.close();
        return true;
    } catch (IOException e) {
        throw new RuntimeException("IOException occurred. ", e);
    } finally {
        if (fileWriter != null) {
            try {
                fileWriter.close();
            } catch (IOException e) {
                throw new RuntimeException("IOException occurred. ", e);
            }
        }
    }
}

From source file:Main.java

/**
 * Serializes the given XML sub-tree to the given file.
 * /* w w w  . j a  v a2s . c o m*/
 * @param xml
 *            The XML tree to serialize - must be a Document or Element.
 * @param file
 *            The file to write to. If it already exists, its contents will
 *            be overwritten; if it does not, it will be created.
 * @param printHeader
 *            True if the standard XML document header should be added to
 *            the top of the file.
 * @throws IOException
 *             <ul>
 *             <li>If there is an error creating, opening, or while writing
 *             to the file.</li>
 *             </ul>
 * @see #toString(Node, boolean)
 */
public static void toFile(final Node xml, final File file, final boolean printHeader) throws IOException {
    final String xmlString = toString(xml, printHeader);

    final FileWriter writer = new FileWriter(file);
    writer.write(xmlString);
    writer.close();
}

From source file:fll.web.WebTestUtils.java

private static void checkForServerError(final Page page) throws IOException {
    final com.gargoylesoftware.htmlunit.WebResponse response = page.getWebResponse();
    final int code = response.getStatusCode();
    final boolean error;
    if (code >= 400) {
        error = true;/*from   w  w w.  j  av a  2s  . c o  m*/
    } else {
        error = false;
    }
    if (error) {
        final String responseMessage = response.getStatusMessage();
        final String text = getPageSource(page);
        final File output = File.createTempFile("server-error", ".html", new File("screenshots"));
        final FileWriter writer = new FileWriter(output);
        writer.write(text);
        writer.close();
        Assert.fail("Error loading page: " + page.getUrl() + " code: " + code + " message: " + responseMessage
                + " Contents of error page written to: " + output.getAbsolutePath());
    }

}

From source file:fll.web.WebTestUtils.java

/**
 * Submit a query to developer/QueryHandler, parse the JSON and return it.
 */// ww  w . j  a va  2  s.co m
public static QueryHandler.ResultData executeServerQuery(final String query) throws IOException, SAXException {
    final WebClient conversation = getConversation();

    final URL url = new URL(TestUtils.URL_ROOT + "developer/QueryHandler");
    final WebRequest request = new WebRequest(url);
    request.setRequestParameters(
            Collections.singletonList(new NameValuePair(QueryHandler.QUERY_PARAMETER, query)));

    final Page response = loadPage(conversation, request);
    final String contentType = response.getWebResponse().getContentType();
    if (!"application/json".equals(contentType)) {
        final String text = getPageSource(response);
        final File output = File.createTempFile("json-error", ".html", new File("screenshots"));
        final FileWriter writer = new FileWriter(output);
        writer.write(text);
        writer.close();
        Assert.fail("Error JSON from QueryHandler: " + response.getUrl()
                + " Contents of error page written to: " + output.getAbsolutePath());
    }

    final String responseData = getPageSource(response);

    final ObjectMapper jsonMapper = new ObjectMapper();
    QueryHandler.ResultData result = jsonMapper.readValue(responseData, QueryHandler.ResultData.class);
    Assert.assertNull("SQL Error: " + result.getError(), result.getError());

    return result;
}

From source file:com.amazonaws.util.FileUtils.java

/**
 * Appends the given data to the file specified in the input and returns the
 * reference to the file.//from w ww  . ja va2  s.c  om
 * 
 * @param file
 * @param dataToAppend
 * @return reference to the file.
 * @throws IOException
 */
public static File appendDataToTempFile(File file, String dataToAppend) throws IOException {
    FileWriter outputWriter = new FileWriter(file);

    try {
        outputWriter.append(dataToAppend);
    } finally {
        outputWriter.close();
    }

    return file;
}

From source file:Util.java

public static boolean retreiveTextFileFromJar(String resourceName, String targetDirectory) throws Exception {
    boolean found = false;
    if (resourceName != null) {
        InputStream is = Util.class.getResourceAsStream(resourceName);
        if (is == null)
            logger.log(Level.WARNING, "The resource '" + resourceName + "' was not found.");
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line;/*  w ww . j  a  v  a 2s . c  o m*/
        String lineSep = System.getProperty("line.separator");
        StringBuffer sb = new StringBuffer();
        while ((line = br.readLine()) != null) {
            sb.append(line);
            sb.append(lineSep);
        }
        is.close();
        if (sb != null) {
            if (sb.length() > 0) {
                FileWriter temp = new FileWriter(targetDirectory + File.separator + resourceName);
                temp.write(sb.toString());
                temp.close();
                found = true;
            }
        }
    }
    return (found);
}