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:Main.java

public static void getStringFromXML(Node node, String dtdFilename, String outputFileName)
        throws TransformerException, IOException {
    File file = new File(outputFileName);
    if (!file.isFile())
        file.createNewFile();/*from  w  w w .jav a  2  s  .c o  m*/
    BufferedWriter out = new BufferedWriter(new FileWriter(file));

    String workingPath = System.setProperty("user.dir", file.getAbsoluteFile().getParent());
    try {
        getStringFromXML(node, dtdFilename, out);
    } finally {
        System.setProperty("user.dir", workingPath);
    }

    out.flush();
    out.close();
}

From source file:PipedCharacters.java

public static void writeStuff(Writer rawOut) {
    try {/*from w ww.  java 2  s.  c  o  m*/
        BufferedWriter out = new BufferedWriter(rawOut);

        String[][] line = { { "Java", "Source", "and", "Support." } };

        for (int i = 0; i < line.length; i++) {
            String[] word = line[i];

            for (int j = 0; j < word.length; j++) {
                out.write(word[j]);
            }

            out.newLine();
        }

        out.flush();
        out.close();
    } catch (IOException x) {
        x.printStackTrace();
    }
}

From source file:common.Utilities.java

public static boolean writeStringToFile(String filename, String stringToWrite) {
    try {//  w w w  .j ava2 s.  co m
        FileWriter writer = new FileWriter(new File(filename));
        BufferedWriter bw = new BufferedWriter(writer);
        bw.write(stringToWrite);
        bw.flush();
        bw.close();
        return true;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return false;
}

From source file:com.sciaps.utils.Util.java

public static void saveCSVFile(StringBuilder strBuilder) {
    JFileChooser chooser = new JFileChooser();

    int retrival = chooser.showSaveDialog(Constants.MAIN_FRAME);
    if (retrival == JFileChooser.APPROVE_OPTION) {

        ProgressStatusPanel progressbar = new ProgressStatusPanel();
        final CustomDialog progressDialog = new CustomDialog(Constants.MAIN_FRAME, "Exporting CSV file",
                progressbar, CustomDialog.NONE_OPTION);
        progressDialog.setSize(400, 100);
        SwingUtilities.invokeLater(new Runnable() {

            @Override//  w ww. j  av a  2 s.c o m
            public void run() {
                progressDialog.setVisible(true);
            }
        });

        try {
            String fileName = chooser.getSelectedFile().toString();
            if (!fileName.endsWith(".csv") && !fileName.endsWith(".CSV")) {
                fileName = fileName + ".csv";
            }
            FileWriter fw = new FileWriter(fileName);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(strBuilder.toString());
            bw.close();
        } catch (Exception ex) {
            ex.printStackTrace();
            System.out.println(ex.getMessage());
        }

        progressDialog.dispose();
    }
}

From source file:com.csipsimple.utils.SipProfileJson.java

/**
 * Save current sip configuration/*from  www. java 2s  .  com*/
 * @param ctxt
 * @return
 */
public static boolean saveSipConfiguration(Context ctxt) {
    File dir = PreferencesWrapper.getConfigFolder();
    if (dir != null) {
        Date d = new Date();
        File file = new File(dir.getAbsoluteFile() + File.separator + "backup_"
                + DateFormat.format("MM-dd-yy_kkmmss", d) + ".json");
        Log.d(THIS_FILE, "Out dir " + file.getAbsolutePath());

        JSONObject configChain = new JSONObject();
        try {
            configChain.put(KEY_ACCOUNTS, serializeSipProfiles(ctxt));
        } catch (JSONException e) {
            Log.e(THIS_FILE, "Impossible to add profiles", e);
        }
        try {
            configChain.put(KEY_SETTINGS, serializeSipSettings(ctxt));
        } catch (JSONException e) {
            Log.e(THIS_FILE, "Impossible to add profiles", e);
        }

        try {
            // Create file
            FileWriter fstream = new FileWriter(file.getAbsoluteFile());
            BufferedWriter out = new BufferedWriter(fstream);
            out.write(configChain.toString(2));
            // Close the output stream
            out.close();
            return true;
        } catch (Exception e) {
            // Catch exception if any
            Log.e(THIS_FILE, "Impossible to save config to disk", e);
            return false;
        }
    }
    return false;
}

From source file:localization.split.java

public static boolean splitFile(String filepath, String passoloPath, boolean myesri) {
    File log = null;/* w w w .  jav  a 2  s .c  om*/
    try {
        String path = filepath.substring(filepath.lastIndexOf("\\") + 1, filepath.length());
        String folder = filepath.substring(0, filepath.lastIndexOf("\\"));
        String[] files = null;
        Vector<String> zFile;
        if (filepath.endsWith(".zip")) {
            zFile = readzipfile(filepath);
            for (String s : zFile) {
                if (s.endsWith(".lpu")) {
                    File unzipFolder = new File(s.substring(0, s.lastIndexOf("\\")));
                    splitFile(s, passoloPath, myesri);
                }
            }
        } else if (!filepath.endsWith(".lpu")) {
            return false;
        } else {
            if (!checkLPU(filepath, passoloPath)) {
                return false;
            }
            File ECI = new File(folder + "\\ECI");
            File AAC = new File(folder + "\\AAC");
            File TOIN = new File(folder + "\\TOIN");
            File LOIX = new File(folder + "\\LIOX");
            if (!ECI.exists()) {
                ECI.mkdir();
            }
            if (!AAC.exists()) {
                AAC.mkdir();
            }
            if (!TOIN.exists()) {
                TOIN.mkdir();
            }
            if (!LOIX.exists()) {
                LOIX.mkdir();
            }
            if (myesri == true) {
                files = new String[4];
                files[0] = folder + "\\ECI\\" + path.substring(0, path.lastIndexOf(".")) + "_ECI.lpu";
                files[1] = folder + "\\AAC\\" + path.substring(0, path.lastIndexOf(".")) + "_AAC.lpu";
                files[2] = folder + "\\TOIN\\" + path.substring(0, path.lastIndexOf(".")) + "_TOIN.lpu";
                files[3] = folder + "\\LIOX\\" + path.substring(0, path.lastIndexOf(".")) + "_LIOX.lpu";

                File srcDir = new File(filepath);
                File trgDir1 = new File(files[0]);
                File trgDir2 = new File(files[1]);
                File trgDir3 = new File(files[2]);
                File trgDir4 = new File(files[3]);
                try {
                    FileUtils.copyFile(srcDir, trgDir1);
                    FileUtils.copyFile(srcDir, trgDir2);
                    FileUtils.copyFile(srcDir, trgDir3);
                    FileUtils.copyFile(srcDir, trgDir4);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                files = new String[6];
                files[0] = folder + "\\ECI\\" + path.substring(0, path.lastIndexOf(".")) + "_ECI.lpu";
                files[1] = folder + "\\ECI\\" + path.substring(0, path.lastIndexOf(".")) + "_ECI_10.lpu";
                files[2] = folder + "\\AAC\\" + path.substring(0, path.lastIndexOf(".")) + "_AAC.lpu";
                files[3] = folder + "\\TOIN\\" + path.substring(0, path.lastIndexOf(".")) + "_TOIN.lpu";
                files[4] = folder + "\\LIOX\\" + path.substring(0, path.lastIndexOf(".")) + "_LIOX_10.lpu";
                files[5] = folder + "\\LIOX\\" + path.substring(0, path.lastIndexOf(".")) + "_LIOX.lpu";

                File srcDir = new File(filepath);
                File trgDir1 = new File(files[0]);
                File trgDir2 = new File(files[1]);
                File trgDir3 = new File(files[2]);
                File trgDir4 = new File(files[3]);
                File trgDir5 = new File(files[4]);
                File trgDir6 = new File(files[5]);
                try {
                    FileUtils.copyFile(srcDir, trgDir1);
                    FileUtils.copyFile(srcDir, trgDir2);
                    FileUtils.copyFile(srcDir, trgDir3);
                    FileUtils.copyFile(srcDir, trgDir4);
                    FileUtils.copyFile(srcDir, trgDir5);
                    FileUtils.copyFile(srcDir, trgDir6);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            String logfile = folder + "\\" + path.substring(path.lastIndexOf("\\") + 1, path.lastIndexOf("."))
                    + ".log";
            log = new File(logfile);
            if (!log.exists()) {
                log.createNewFile();
            }

            for (int i = 0; i < files.length; i++) {
                int exitVal = 0;
                try {
                    String osName = System.getProperty("os.name");
                    String cmd = "cmd.exe /c " + passoloPath + " /openproject:" + files[i]
                            + " /runmacro=PslLpuSplitter_v3.bas" + " >> " + logfile;
                    System.out.println(cmd);
                    Runtime rt = Runtime.getRuntime();
                    Process proc = rt.exec(cmd);
                    exitVal = proc.waitFor();
                    System.out.println("Exit value: " + exitVal);
                    if (exitVal == 10) {
                        return false;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                File lpuFile = new File(files[i]);
                File logFile = new File(files[i].substring(0,
                        files[i].substring(0, files[i].lastIndexOf("\\")).lastIndexOf("\\") + 1)
                        + files[i].substring(files[i].lastIndexOf("\\") + 1, files[i].lastIndexOf("."))
                        + ".log");
                if (!lpuFile.exists()) {
                    logFile.delete();
                }
                File lpuFolder = new File(files[i].substring(0, files[i].lastIndexOf("\\")));
                if (lpuFolder.list().length == 0) {
                    lpuFolder.delete();
                }
            } // end for loop  
        }

    } catch (Exception e) {
        try {
            String content = e.getMessage();
            FileWriter fw = new FileWriter(log.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(content);
            bw.close();
        } catch (Exception e1) {

        }

        return false;
    }
    return true;
}

From source file:com.example.makerecg.NetworkUtilities.java

/**
 * Connects to the SampleSync test server, authenticates the provided
 * username and password./* w w  w.j  a va  2s.  com*/
 * This is basically a standard OAuth2 password grant interaction.
 *
 * @param username The server account username
 * @param password The server account password
 * @return String The authentication token returned by the server (or null)
 */
public static String authenticate(String username, String password) {
    String token = null;

    try {

        Log.i(TAG, "Authenticating to: " + AUTH_URI);
        URL urlToRequest = new URL(AUTH_URI);
        HttpURLConnection conn = (HttpURLConnection) urlToRequest.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("grant_type", "password"));
        params.add(new BasicNameValuePair("client_id", "CLIENT_ID"));
        params.add(new BasicNameValuePair("username", username));
        params.add(new BasicNameValuePair("password", password));

        OutputStream os = conn.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        writer.write(getQuery(params));
        writer.flush();
        writer.close();
        os.close();

        int responseCode = conn.getResponseCode();

        if (responseCode == HttpsURLConnection.HTTP_OK) {
            String response = "";
            String line;
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            while ((line = br.readLine()) != null) {
                response += line;
            }
            br.close();

            // Response body will look something like this:
            // {
            //    "token_type": "bearer",
            //    "access_token": "0dd18fd38e84fb40e9e34b1f82f65f333225160a",
            //    "expires_in": 3600
            //  }

            JSONObject jresp = new JSONObject(new JSONTokener(response));

            token = jresp.getString("access_token");
        } else {
            Log.e(TAG, "Error authenticating");
            token = null;
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        Log.v(TAG, "getAuthtoken completing");
    }

    return token;

}

From source file:com.example.makerecg.NetworkUtilities.java

/**
 * Perform 2-way sync with the server-side ADSampleFrames. We send a request that
 * includes all the locally-dirty contacts so that the server can process
 * those changes, and we receive (and return) a list of contacts that were
 * updated on the server-side that need to be updated locally.
 *
 * @param account The account being synced
 * @param authtoken The authtoken stored in the AccountManager for this
 *            account//from w  w  w  .  j  a va2s  .c  o m
 * @param serverSyncState A token returned from the server on the last sync
 * @param dirtyFrames A list of the frames to send to the server
 * @return A list of frames that we need to update locally
 */
public static List<ADSampleFrame> syncSampleFrames(Account account, String authtoken, long serverSyncState,
        List<ADSampleFrame> dirtyFrames)
        throws JSONException, ParseException, IOException, AuthenticationException {

    List<JSONObject> jsonFrames = new ArrayList<JSONObject>();
    for (ADSampleFrame frame : dirtyFrames) {
        jsonFrames.add(frame.toJSONObject());
    }

    JSONArray buffer = new JSONArray(jsonFrames);
    JSONObject top = new JSONObject();

    top.put("data", buffer);

    // Create an array that will hold the server-side ADSampleFrame
    // that have been changed (returned by the server).
    final ArrayList<ADSampleFrame> serverDirtyList = new ArrayList<ADSampleFrame>();

    // Send the updated frames data to the server
    //Log.i(TAG, "Syncing to: " + SYNC_URI);
    URL urlToRequest = new URL(SYNC_URI);
    HttpURLConnection conn = (HttpURLConnection) urlToRequest.openConnection();
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/json");
    conn.setRequestProperty("Authorization", "Bearer " + authtoken);

    OutputStream os = conn.getOutputStream();
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
    writer.write(top.toString(1));
    writer.flush();
    writer.close();
    os.close();

    //Log.i(TAG, "body="+top.toString(1));

    int responseCode = conn.getResponseCode();

    if (responseCode == HttpsURLConnection.HTTP_OK) {
        // Our request to the server was successful - so we assume
        // that they accepted all the changes we sent up, and
        // that the response includes the contacts that we need
        // to update on our side...

        // TODO: Only uploading data for now ...

        String response = "";
        String line;
        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        while ((line = br.readLine()) != null) {
            response += line;
        }
        br.close();

        //Log.i(TAG, "response="+response);
        /*
        final JSONArray serverContacts = new JSONArray(response);
        Log.d(TAG, response);
        for (int i = 0; i < serverContacts.length(); i++) {
        ADSampleFrame rawContact = ADSampleFrame.valueOf(serverContacts.getJSONObject(i));
        if (rawContact != null) {
            serverDirtyList.add(rawContact);
        }
        }
        */
    } else {
        if (responseCode == HttpsURLConnection.HTTP_UNAUTHORIZED) {
            Log.e(TAG, "Authentication exception in while uploading data");
            throw new AuthenticationException();
        } else {
            Log.e(TAG, "Server error in sending sample frames: " + responseCode);
            throw new IOException();
        }
    }

    return null;
}

From source file:ProxyAuthTest.java

private static void generateData() throws Exception {
    String fileData[] = { "1|aaa", "2|bbb", "3|ccc", "4|ddd", "5|eee", };

    File tmpFile = File.createTempFile(tabName, ".data");
    tmpFile.deleteOnExit();//w  w  w . jav a2 s. c  om
    tabDataFileName = tmpFile.getPath();
    FileWriter fstream = new FileWriter(tabDataFileName);
    BufferedWriter out = new BufferedWriter(fstream);
    for (String line : fileData) {
        out.write(line);
        out.newLine();
    }
    out.close();
    tmpFile.setWritable(true, true);
}

From source file:com.jaceace.utils.Bundle.java

public static boolean write(Bundle bundle, OutputStream stream) {
    try {/*from   ww w  .j a  v a2s  .  co m*/
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stream));
        writer.write(bundle.data.toString());
        writer.close();

        return true;
    } catch (IOException e) {
        return false;
    }
}