Example usage for java.io BufferedWriter BufferedWriter

List of usage examples for java.io BufferedWriter BufferedWriter

Introduction

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

Prototype

public BufferedWriter(Writer out) 

Source Link

Document

Creates a buffered character-output stream that uses a default-sized output buffer.

Usage

From source file:jetbrains.exodus.util.Streamer.java

public Streamer(@NotNull InputStream socketInput, @NotNull OutputStream socketOutput) {
    this.socketInput = new BufferedReader(new InputStreamReader(socketInput), BUFFER_SIZE);
    this.socketOutput = new BufferedWriter(new OutputStreamWriter(socketOutput));
}

From source file:com.github.megatronking.stringfog.plugin.StringFogMappingPrinter.java

void startMappingOutput() {
    try {// ww w  .  j  a va  2 s.c o m
        if (mMappingFile.exists() && !mMappingFile.delete()) {
            throw new IOException();
        }
        File dir = mMappingFile.getParentFile();
        if (dir.exists() || dir.mkdirs()) {
            mWriter = new BufferedWriter(new FileWriter(mMappingFile));
        } else {
            throw new IOException();
        }
    } catch (IOException e) {
        Log.e("Create stringfog mapping file failed.");
    }
}

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 ww w.ja  v a 2  s  .  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:de.tudarmstadt.ukp.dkpro.tc.crfsuite.writer.CRFSuiteDataWriter.java

public static File writeFeatureFile(FeatureStore featureStore, File aOutputDirectory) throws Exception {
    int totalCountOfInstances = featureStore.getNumberOfInstances();

    File outputFile = new File(aOutputDirectory,
            CRFSuiteAdapter.getInstance().getFrameworkFilename(AdapterNameEntries.featureVectorsFile));
    outputFile.deleteOnExit();//from w w  w . j  ava 2 s . co  m

    BufferedWriter bf = new BufferedWriter(new FileWriter(outputFile));

    int lastSeenSeqId = -1;
    boolean seqIdChanged = false;
    for (int ins = 0; ins < totalCountOfInstances; ins++) {
        Instance i = featureStore.getInstance(ins);

        if (i.getSequenceId() != lastSeenSeqId) {
            seqIdChanged = true;
            lastSeenSeqId = i.getSequenceId();
        }

        bf.write(LabelSubstitutor.labelReplacement(i.getOutcome()));
        bf.write("\t");

        List<Feature> features = i.getFeatures();
        for (int idx = 0; idx < features.size(); idx++) {
            Feature f = features.get(idx);
            bf.write(f.getName() + "=" + f.getValue());
            if (idx + 1 < features.size()) {
                bf.write("\t");
            }
        }

        // Mark first line of new sequence with an additional __BOS__
        if (seqIdChanged) {
            bf.write("\t");
            bf.write("__BOS__");
            seqIdChanged = false;
        }

        // Peak ahead - seqEnd reached?
        if (ins + 1 < totalCountOfInstances) {
            Instance next = featureStore.getInstance(ins + 1);
            if (next.getSequenceId() != lastSeenSeqId) {
                appendEOS(bf);
                continue;
            }
        } else if (ins + 1 == totalCountOfInstances) {
            appendEOS(bf);
        }

        bf.write("\n");
    }
    bf.close();

    return outputFile;
}

From source file:com.sat.common.SDdetails.java

public static void sdStatus(String SDip) throws IOException, FileNotFoundException, ClientProtocolException {
    new FileOutputStream(htmlfname).close();
    htmlfile = new PrintWriter(new BufferedWriter(new FileWriter(htmlfname, true)));

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpGet getRequest = new HttpGet("http://" + SDip + ":2013/service");

    HttpResponse response = httpClient.execute(getRequest);

    BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

    String output;/*ww  w .  ja v a2 s  .co m*/
    String q = null;
    System.out.println("SD details .... \n");
    while ((output = br.readLine()) != null) {
        q = output;
        //   System.out.println(output);
    }
    httpClient.getConnectionManager().shutdown();
    parserGson(q);
    //htmlfile.close();
}

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  w  w  .j  av  a 2 s  . c om
    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.uksf.mf.core.utility.LogHandler.java

/**
 * Writes to file//  w ww.j  a  v  a2 s. co m
 * @param log formatted message to write
 */
private static void toFile(String log) {
    try {
        Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(logFile, true)));
        writer.append(log).append("\n");
        writer.close();
    } catch (IOException e) {
        error(e);
    }
}

From source file:fitnesse.slim.SlimClient.java

public void connect() throws IOException {
    try {/*from  ww  w  . ja va  2s  . c  o  m*/
        for (int tries = 0; !tryConnect(); tries++) {
            if (tries > 100)
                throw new SlimError("Could not start Slim.");
            Thread.sleep(50);
        }
    } catch (InterruptedException e) {
        throw new SlimError("Interrupted while attempting to connect", e);
    }
    reader = new StreamReader(client.getInputStream());
    try {
        writer = new BufferedWriter(new OutputStreamWriter(client.getOutputStream(), "UTF-8"));
    } catch (UnsupportedEncodingException e) {
        throw new ImpossibleException("UTF-8 is a supported encoding", e);
    }
    slimServerVersionMessage = reader.readLine();
    slimServerVersion = isConnected() ? Double.parseDouble(slimServerVersionMessage.replace("Slim -- V", ""))
            : -1;
}

From source file:com.amazonaws.services.dynamodbv2.online.index.ViolationWriter.java

public void createOutputFile(String outputFilePath) throws IOException {
    File outputFile = new File(outputFilePath);
    if (outputFile.exists()) {
        outputFile.delete();//from   www . jav a 2 s. com
    }
    outputFile.createNewFile();
    FileWriter out = new FileWriter(outputFilePath, true);
    bufferWriter = new BufferedWriter(out);
    printer = new CSVPrinter(bufferWriter, format);
}

From source file:net.arccotangent.pacchat.net.KeyUpdateClient.java

public void run() {
    Socket socket;/*from  w w w.  j ava2 s.  c om*/
    BufferedReader input;
    BufferedWriter output;

    kuc_log.i("Connecting to server at " + server_ip);

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

    try {
        kuc_log.i("Requesting a key update.");
        output.write("302 request key update");
        output.newLine();
        output.flush();

        kuc_log.i("Awaiting response from server.");
        String update = input.readLine();
        switch (update) {
        case "303 update":
            kuc_log.i("Server accepted update request, sending public key.");
            String pubkeyB64 = Base64.encodeBase64String(Main.getKeypair().getPublic().getEncoded());
            output.write(pubkeyB64);
            output.newLine();
            output.flush();
            output.close();
            break;
        case "304 no update":
            kuc_log.i("Server rejected update request, closing connection.");
            input.close();
            output.close();
            break;
        case "305 update unavailable":
            kuc_log.i("Server cannot update at this time, try again later.");
            input.close();
            output.close();
            break;
        default:
            kuc_log.i("Server sent back invalid response");
            input.close();
            output.close();
            break;
        }
    } catch (IOException e) {
        kuc_log.e("Error in key update request!");
        e.printStackTrace();
    }
}