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:de.fau.amos.FileDownload.java

/**
 * Creates a .csv file containing the data of the passed "ArrayList<ArrayList<String>> data" and saves it into the "userdir.location" directory
 * @param data//from   ww  w . j a  va  2 s . c om
 * @param fileName
 */
private static void createCsvFile(ArrayList<ArrayList<String>> data, String fileName) {

    try {
        String lines = "";

        //using Buffered Writer to write a file into the "userdir.location" directory
        BufferedWriter bw = new BufferedWriter(
                new FileWriter(new File(System.getProperty("userdir.location"), fileName)));

        //every single value will be written down into the file separated by a semicolon
        for (int i = 0; i < data.size(); i++) {
            for (int j = 0; j < data.get(i).size(); j++) {
                lines = data.get(i).get(j) + "; ";
                bw.write(lines);
            }
            bw.newLine();

        }
        bw.flush();
        bw.close();

        System.out.println("Success!");
    } catch (IOException e) {
        System.out.println("Couldn't create File!");
    }
}

From source file:com.k_joseph.apps.multisearch.solr.AddCustomFieldsToSchema.java

/**
 * Reads the schema file line by line and edits it to add a new field entry
 * /*www .  j  av  a 2 s.  com*/
 * @param schemaFileLocation
 * @param fieldEntry, the field entry line, use
 *            {@link #generateAWellWrittenFieldEntry(String, String, boolean, boolean, boolean)}
 * @return new lines of the file in a List
 */
public static void readSchemaFileLineByLineAndWritNewFieldEntries(String schemaFileLocation,
        String newSchemaFilePath, String fieldEntry, String copyFieldEntry, SolrServer solrServer) {
    //reading file line by line in Java using BufferedReader       
    FileInputStream fis = null;
    BufferedReader reader = null;
    boolean replacedSchemaWithBackUp = replaceSchemaFileWithItsBackup(schemaFileLocation);
    if (replacedSchemaWithBackUp) {
        System.out.println("Successfully replaced the schema.xml file with a previously backed-up copy");
    }
    try {
        fis = new FileInputStream(schemaFileLocation);
        reader = new BufferedReader(new InputStreamReader(fis));

        System.out.println("Reading " + schemaFileLocation + " file line by line using BufferedReader");
        File newSchemaFile = new File(newSchemaFilePath);
        if (newSchemaFile.exists())
            newSchemaFile.delete();
        String line = reader.readLine();
        while (line != null) {
            FileWriter fileWritter = new FileWriter(newSchemaFile, true);
            BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
            //write to the file from here.
            if (line.equals("\t\t<!-- Fields from modules and other projects starts here -->")) {
                bufferWritter.write("\t\t<!-- Fields from modules and other projects starts here -->\n"
                        + fieldEntry + "\n");
                bufferWritter.close();
            } else if (line.equals("\t<!-- Starting customly added copyfields -->")) {
                bufferWritter
                        .write("\n\t<!-- Starting customly added copyfields -->\n" + copyFieldEntry + "\n");
                bufferWritter.close();
            } else {
                bufferWritter.write(line + "\n");
                bufferWritter.close();
            }

            line = reader.readLine();
        }

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

    } finally {
        try {
            reader.close();
            fis.close();
        } catch (IOException ex) {
            Logger.getLogger(AddCustomFieldsToSchema.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    copyNewSchemaFileToPreviouslyUsed(schemaFileLocation, newSchemaFilePath);
    CoreAdminRequest adminRequest = new CoreAdminRequest();
    reloadSolrServer(solrServer, adminRequest);
}

From source file:com.microsoft.alm.plugin.idea.common.setup.WindowsStartup.java

/**
 * Create VB script to run KeyCreator application as elevated
 *
 * @param newCmd//from w w  w  .  ja v  a  2  s  .  c  o m
 * @return script file
 * @throws IOException
 */
protected static File createRegeditFile(final File newCmd) throws IOException {
    final File script = File.createTempFile("CreateKeys", ".reg");
    final FileWriter fileWriter = new FileWriter(script);
    final BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
    try {
        bufferedWriter.write("Windows Registry Editor Version 5.00\r\n\r\n"
                + "[-HKEY_CLASSES_ROOT\\vsoi]\r\n\r\n" + "[HKEY_CLASSES_ROOT\\vsoi]\r\n"
                + "\"URL Protocol\"=\"\"\r\n\r\n" + "[HKEY_CLASSES_ROOT\\vsoi\\Shell\\Open\\Command]\r\n"
                + "\"\"=\"" + newCmd.getPath().replace("\\", "\\\\") + " \\\"%1\\\" \"");
    } finally {
        if (bufferedWriter != null) {
            bufferedWriter.close();
        }
    }
    return script;
}

From source file:com.raphfrk.craftproxyclient.net.auth.AuthManager.java

@SuppressWarnings("unchecked")
public static void authServer17(String hash) throws IOException {
    URL url;//from   w  w w . j  av  a2  s  .  c  om
    String username;
    String accessToken;
    try {
        if (loginDetails == null) {
            throw new IOException("Not logged in");
        }

        try {
            username = URLEncoder.encode(getUsername(), "UTF-8");
            accessToken = URLEncoder.encode(getAccessToken(), "UTF-8");
            hash = URLEncoder.encode(hash, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new IOException("Username/password encoding error", e);
        }

        String urlString;
        urlString = sessionServer17;
        url = new URL(urlString);
    } catch (MalformedURLException e) {
        throw new IOException("Auth server URL error", e);
    }
    HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
    con.setDoOutput(true);
    con.setInstanceFollowRedirects(false);
    con.setReadTimeout(5000);
    con.setConnectTimeout(5000);
    con.setRequestMethod("POST");
    con.setRequestProperty("Content-Type", "application/json");
    con.connect();

    JSONObject obj = new JSONObject();
    obj.put("accessToken", accessToken);
    obj.put("selectedProfile", loginDetails.get("selectedProfile"));
    obj.put("serverId", hash);
    BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(con.getOutputStream(), StandardCharsets.UTF_8));
    try {
        obj.writeJSONString(writer);
        writer.flush();
        writer.close();
    } catch (IOException e) {
        if (writer != null) {
            writer.close();
            con.disconnect();
            return;
        }
    }
    if (con.getResponseCode() != 200) {
        throw new IOException("Unable to verify username, please restart proxy");
    }
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8));
    try {
        String reply = reader.readLine();
        if (reply != null) {
            throw new IOException("Auth server replied (" + reply + ")");
        }
    } finally {
        reader.close();
        con.disconnect();
    }
}

From source file:com.hazelcast.simulator.utils.FileUtils.java

public static void writeText(String text, File file) {
    if (text == null) {
        throw new NullPointerException("text can't be null");
    }/*w w w  . j  av a2 s. co  m*/

    if (file == null) {
        throw new NullPointerException("file can't be null");
    }

    FileOutputStream stream = null;
    OutputStreamWriter streamWriter = null;
    BufferedWriter writer = null;
    try {
        stream = new FileOutputStream(file);
        streamWriter = new OutputStreamWriter(stream);
        writer = new BufferedWriter(streamWriter);
        writer.write(text);
        writer.close();
    } catch (IOException e) {
        throw new FileUtilsException(e);
    } finally {
        closeQuietly(writer);
        closeQuietly(streamWriter);
        closeQuietly(stream);
    }
}

From source file:cloudclient.Client.java

public static void batchReceiveResp(BufferedReader in) throws IOException, ParseException {
    BufferedWriter bw = new BufferedWriter(new FileWriter("result.txt"));

    JSONParser parser = new JSONParser();

    String message;/*w w  w . j  a v a2 s. c om*/
    while ((message = in.readLine()) != null) {
        //System.out.println(message);
        JSONArray responseList = (JSONArray) parser.parse(message);

        for (int i = 0; i < responseList.size(); i++) {
            JSONObject response = (JSONObject) responseList.get(i);
            bw.write(response.get("URL").toString());
            bw.newLine();
        }
    }

    bw.close();

}

From source file:com.hazelcast.simulator.utils.FileUtils.java

public static void appendText(String text, File file) {
    if (text == null) {
        throw new NullPointerException("Text can't be null");
    }//  ww w.  j  a va  2s .  c  o  m
    if (file == null) {
        throw new NullPointerException("File can't be null");
    }

    FileOutputStream stream = null;
    OutputStreamWriter streamWriter = null;
    BufferedWriter writer = null;
    try {
        stream = new FileOutputStream(file, true);
        streamWriter = new OutputStreamWriter(stream);
        writer = new BufferedWriter(streamWriter);
        writer.append(text);
        writer.close();
    } catch (IOException e) {
        throw new FileUtilsException("Could not append text", e);
    } finally {
        closeQuietly(writer);
        closeQuietly(streamWriter);
        closeQuietly(stream);
    }
}

From source file:com.raphfrk.craftproxyclient.net.auth.AuthManager.java

public static JSONObject sendRequest(JSONObject request, String endpoint) {
    URL url;/*  w  w w.j av a 2 s. com*/
    try {
        url = new URL(authServer + "/" + endpoint);
    } catch (MalformedURLException e) {
        return null;
    }
    try {
        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
        con.setDoOutput(true);
        con.setInstanceFollowRedirects(false);
        con.setReadTimeout(5000);
        con.setConnectTimeout(5000);
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/json");
        con.connect();

        BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(con.getOutputStream(), StandardCharsets.UTF_8));
        try {
            request.writeJSONString(writer);
            writer.flush();
            writer.close();

            if (con.getResponseCode() != 200) {
                return null;
            }

            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8));
            try {
                JSONParser parser = new JSONParser();

                try {
                    return (JSONObject) parser.parse(reader);
                } catch (ParseException e) {
                    return null;
                }
            } finally {
                reader.close();
            }
        } finally {
            writer.close();
            con.disconnect();
        }
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }

}

From source file:csv.FileManager.java

static public void writeItems(String fileName, ArrayList<ArrayList<String>> data) {
    try {/*from   w  w w  .  j a  va2 s . co  m*/
        BufferedWriter out = new BufferedWriter(new FileWriter(fileName));
        CSVWriter writer = new CSVWriter(out);
        String[] t = new String[0];
        for (ArrayList<String> row : data) {
            boolean found = false;
            for (String str : row) {
                if (!str.isEmpty()) {
                    found = true;
                }
            }
            if (found)
                writer.writeNext(row.toArray(t));
        }
        out.close();
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

From source file:edgeserver.Publicador.java

private static void armazenaFila(ArrayList filaPublicacoes) throws IOException {
    new PrintWriter("fila.txt").close();
    filaPublicacoes.stream().forEach((publicacao) -> {
        BufferedWriter bw = null;
        try {//from w  w w. ja  v a  2s  .  c  o m
            // APPEND MODE SET HERE
            bw = new BufferedWriter(new FileWriter("fila.txt", true));
            bw.write(publicacao.toString());
            bw.newLine();
            bw.flush();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } finally { // always close the file
            if (bw != null)
                try {
                    bw.close();
                } catch (IOException ioe2) {
                    // just ignore it
                }
        }
    });

}