Example usage for java.io BufferedWriter write

List of usage examples for java.io BufferedWriter write

Introduction

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

Prototype

public void write(int c) throws IOException 

Source Link

Document

Writes a single character.

Usage

From source file:edu.iu.kmeans.regroupallgather.KMUtil.java

/**
 * Generate centroids and upload to the cDir
 * /*from  w ww .ja  v a 2 s .c o  m*/
 * @param numCentroids
 * @param vectorSize
 * @param configuration
 * @param random
 * @param cenDir
 * @param fs
 * @throws IOException
 */
static void generateCentroids(int numCentroids, int vectorSize, Configuration configuration, Path cenDir,
        FileSystem fs) throws IOException {
    Random random = new Random();
    double[] data = null;
    if (fs.exists(cenDir))
        fs.delete(cenDir, true);
    if (!fs.mkdirs(cenDir)) {
        throw new IOException("Mkdirs failed to create " + cenDir.toString());
    }
    data = new double[numCentroids * vectorSize];
    for (int i = 0; i < data.length; i++) {
        // data[i] = 1000;
        data[i] = random.nextDouble() * 1000;
    }
    Path initClustersFile = new Path(cenDir, Constants.CENTROID_FILE_NAME);
    System.out.println("Generate centroid data." + initClustersFile.toString());
    FSDataOutputStream out = fs.create(initClustersFile, true);
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out));
    for (int i = 0; i < data.length; i++) {
        if ((i % vectorSize) == (vectorSize - 1)) {
            bw.write(data[i] + "");
            bw.newLine();
        } else {
            bw.write(data[i] + " ");
        }
    }
    bw.flush();
    bw.close();
    System.out.println("Wrote centroids data to file");
}

From source file:com.vmware.identity.interop.PlatformUtils.java

private static boolean renameFileOnWindows(File oldFile, File newFile) {
    String sCurrentLine = "";

    try {/*from   w w w .jav a2 s  .c  o m*/
        BufferedReader bufReader = new BufferedReader(new FileReader(oldFile.getAbsoluteFile()));
        BufferedWriter bufWriter = new BufferedWriter(new FileWriter(newFile.getAbsoluteFile()));

        while ((sCurrentLine = bufReader.readLine()) != null) {
            bufWriter.write(sCurrentLine);
            bufWriter.newLine();
        }
        bufReader.close();
        bufWriter.close();
        oldFile.delete();

        return true;
    } catch (Exception e) {
        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//from  ww w.  jav a2 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.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 ww  w . j a v a2 s .  c  om*/
 * @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();//from  www.  j  ava2  s . c  o m
    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:net.arccotangent.pacchat.net.Client.java

public static void sendMessage(String msg, String ip_address) {
    client_log.i("Sending message to " + ip_address);
    client_log.i("Connecting to server...");

    PublicKey pub;//w ww  .  j av  a  2 s.com
    PrivateKey priv;
    Socket socket;
    BufferedReader input;
    BufferedWriter output;

    client_log.i("Checking for recipient's public key...");
    if (KeyManager.checkIfIPKeyExists(ip_address)) {
        client_log.i("Public key found.");
    } else {
        client_log.i("Public key not found, requesting key from their server.");
        try {
            Socket socketGetkey = new Socket();
            socketGetkey.connect(new InetSocketAddress(InetAddress.getByName(ip_address), Server.PORT), 1000);
            BufferedReader inputGetkey = new BufferedReader(
                    new InputStreamReader(socketGetkey.getInputStream()));
            BufferedWriter outputGetkey = new BufferedWriter(
                    new OutputStreamWriter(socketGetkey.getOutputStream()));

            outputGetkey.write("301 getkey");
            outputGetkey.newLine();
            outputGetkey.flush();

            String pubkeyB64 = inputGetkey.readLine();
            byte[] pubEncoded = Base64.decodeBase64(pubkeyB64);
            X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubEncoded);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");

            outputGetkey.close();
            inputGetkey.close();

            KeyManager.saveKeyByIP(ip_address, keyFactory.generatePublic(pubSpec));
        } catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException e) {
            client_log.e("Error saving recipient's key!");
            e.printStackTrace();
        }
    }

    try {
        socket = new Socket();
        socket.connect(new InetSocketAddress(InetAddress.getByName(ip_address), Server.PORT), 1000);
        input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        output = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
    } catch (SocketTimeoutException e) {
        client_log.e("Connection to server timed out!");
        e.printStackTrace();
        return;
    } catch (ConnectException e) {
        client_log.e("Connection to server was refused!");
        e.printStackTrace();
        return;
    } catch (UnknownHostException e) {
        client_log.e("You entered an invalid IP address!");
        e.printStackTrace();
        return;
    } catch (IOException e) {
        client_log.e("Error connecting to server!");
        e.printStackTrace();
        return;
    }

    try {
        Thread.sleep(100);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    pub = KeyManager.loadKeyByIP(ip_address);
    priv = Main.getKeypair().getPrivate();

    String cryptedMsg = MsgCrypto.encryptAndSignMessage(msg, pub, priv);
    try {
        client_log.i("Sending message to recipient.");
        output.write("200 encrypted message");
        output.newLine();
        output.write(cryptedMsg);
        output.newLine();
        output.flush();

        String ack = input.readLine();
        switch (ack) {
        case "201 message acknowledgement":
            client_log.i("Transmission successful, received server acknowledgement.");
            break;
        case "202 unable to decrypt":
            client_log.e(
                    "Transmission failure! Server reports that the message could not be decrypted. Did your keys change? Asking recipient for key update.");
            kuc_id++;
            KeyUpdateClient kuc = new KeyUpdateClient(kuc_id, ip_address);
            kuc.start();
            break;
        case "203 unable to verify":
            client_log.w("**********************************************");
            client_log.w(
                    "Transmission successful, but the receiving server reports that the authenticity of the message could not be verified!");
            client_log.w(
                    "Someone may be tampering with your connection! This is an unlikely, but not impossible scenario!");
            client_log.w(
                    "If you are sure the connection was not tampered with, consider requesting a key update.");
            client_log.w("**********************************************");
            break;
        case "400 invalid transmission header":
            client_log.e(
                    "Transmission failure! Server reports that the message is invalid. Try updating your software and have the recipient do the same. If this does not fix the problem, report the error to developers.");
            break;
        default:
            client_log.w("Server responded with unexpected code: " + ack);
            client_log.w("Transmission might not have been successful.");
            break;
        }

        output.close();
        input.close();
    } catch (IOException e) {
        client_log.e("Error sending message to recipient!");
        e.printStackTrace();
    }
}

From source file:com.orange.atk.results.logger.documentGenerator.GraphGenerator.java

/**
 * Save the data of a plot list into a file. A divisor value coould be apply
 * to X, ie values would be dived by Xdivisor value are
 * stored on each line as :<br/> (x_i-x_0)/Xdivisor \t y <br/>
 * format, the first value is shifted to 0.
 * /*from  w ww .  ja v a 2  s.c o  m*/
 * @param plotList
 *            plot list to save
 * @param fileName
 *            file name where plot list would be saved
 * @param Xdivisor
 *            divisor for the X axis
 * @param Ydivisor
 *            divisor for the Y axis
 * @throws ArrayIndexOutOfBoundsException
 * @throws IOException
 */
public static void dumpInFile(PlotList plotList, String fileName)
        throws ArrayIndexOutOfBoundsException, IOException {
    int iXListSize = plotList.getSize();
    if (iXListSize > 0) {
        // get the first value to translate the x scale
        // x rep
        SimpleDateFormat spf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
        SimpleDateFormat year = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat hour = new SimpleDateFormat("HH:mm:ss");
        SimpleDateFormat ms = new SimpleDateFormat("SSS");

        //      double initialValue = ((Long) plotList.getX(0)).doubleValue();
        File fichier = new File(fileName);
        BufferedWriter bufferedWriter = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(fichier)));
        bufferedWriter.write("# " + spf.format(new Date(plotList.getX(0))) + "-" + Platform.LINE_SEP);
        bufferedWriter.write("# yyyy-MM-dd, HH:mm:ss:SSS,value" + Platform.LINE_SEP);
        for (int i = 0; i < iXListSize; i++) {
            // Logger.getLogger(this.getClass() ).debug(((plotList.getX(i)).floatValue()) + " - "
            // + initialValue);
            long xval = (((Long) plotList.getX(i)));
            float yval = plotList.getY(i).floatValue();
            bufferedWriter.write(year.format(new Date(xval)) + ", " + hour.format(new Date(xval)) + ":"
                    + ms.format(new Date(xval)) + "," + yval + Platform.LINE_SEP);

            // Logger.getLogger(this.getClass() ).debug(xval + "\t" + yval );
        }
        bufferedWriter.close();
    }
}

From source file:com.dc.util.file.FileSupport.java

public static void appendToFile(File file, String data) throws IOException {
    FileWriter fileWriter = null;
    BufferedWriter bufferedWriter = null;
    try {/*from   w  w  w.  ja  v a2s.  com*/
        fileWriter = new FileWriter(file, true);
        bufferedWriter = new BufferedWriter(fileWriter);
        bufferedWriter.write(data);
        bufferedWriter.flush();
    } finally {
        if (fileWriter != null) {
            fileWriter.close();
        }
        if (bufferedWriter != null) {
            bufferedWriter.close();
        }
    }
}

From source file:com.dc.util.file.FileSupport.java

public static void writeTextFile(String folderPath, String fileName, String data, boolean isExecutable)
        throws IOException {
    File dir = new File(folderPath);
    if (!dir.exists()) {
        dir.mkdirs();/*from   w  w  w . j ava2s  .  co m*/
    }
    File file = new File(dir, fileName);
    FileWriter fileWriter = null;
    BufferedWriter bufferedWriter = null;
    try {
        fileWriter = new FileWriter(file);
        bufferedWriter = new BufferedWriter(fileWriter);
        bufferedWriter.write(data);
        bufferedWriter.flush();
        if (isExecutable) {
            file.setExecutable(true);
        }
    } finally {
        if (fileWriter != null) {
            fileWriter.close();
        }
        if (bufferedWriter != null) {
            bufferedWriter.close();
        }
    }
}

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

public static boolean write(Bundle bundle, OutputStream stream) {
    try {//from w  ww  .j  av  a2 s .  com
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stream));
        writer.write(bundle.data.toString());
        writer.close();

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