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:fm.last.commons.io.LastFileUtils.java

/**
 * Appends the passed string to the passed file.
 * /*from   w w  w .j av a2  s  .  c o  m*/
 * @param file File to append string to (will be created if it does not exist).
 * @param string String to append.
 * @throws IOException If an error occurs appending the string to the file.
 */
public static void appendStringToFile(File file, String string) throws IOException {
    BufferedWriter writer = new BufferedWriter(new FileWriter(file, true));
    writer.write(string);
    writer.close();
}

From source file:com.sugarcrm.candybean.datasource.CsvDataAdapterSystemTest.java

private static void createFile(String dir, String filename, String content) {
    try {/* w w  w .jav  a 2s .  c  o m*/
        File file = new File(dir + File.separator + filename);

        // Create file if not exist
        if (!file.exists()) {
            file.createNewFile();
            System.out.println("createFile(): created " + file.getAbsolutePath());
        } else {
            System.out.println("createFile(): " + file.getAbsolutePath() + " already exists");
        }

        FileWriter fw = new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(content);
        bw.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:functionalTests.dataspaces.GCMFunctionalDataSpacesBase.java

private static void createInputFileContent(final File file) throws IOException {
    final File parentFile = file.getParentFile();
    if (!parentFile.exists()) {
        assertTrue(parentFile.mkdirs());
    }/*from   www  . java2  s  . c o  m*/
    final BufferedWriter writer = new BufferedWriter(new FileWriter(file));
    writer.write(INPUT_FILE_CONTENT);
    writer.close();
}

From source file:com.wso2telco.util.FileUtil.java

/**
 * File write.//from  ww w.j a v a2s . c  o m
 *
 * @param filePath the file path
 * @param data the data
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static void fileWrite(String filePath, String data) throws IOException {
    BufferedWriter out = null;
    try {
        out = new BufferedWriter(new FileWriter(filePath));
        out.write(data);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        out.close();
    }

}

From source file:gsn.http.ac.ParameterSet.java

private static void changeSensorName(String filepath, String name) {
    File f = new File(filepath);

    Pattern pat = Pattern.compile("name[\\s]*=[\\s]*\"[\\s]*[\\S]+[\\s]*\"");
    Matcher match;//www. j  a  va  2 s. co  m
    FileInputStream fs = null;
    InputStreamReader in = null;
    BufferedReader br = null;

    StringBuffer sb = new StringBuffer();
    String textinLine;

    try {
        fs = new FileInputStream(f);
        in = new InputStreamReader(fs);
        br = new BufferedReader(in);

        while (true) {
            textinLine = br.readLine();
            if (textinLine == null)
                break;
            if (textinLine.contains("<virtual-sensor")) {
                match = pat.matcher(textinLine);
                match.find();
                textinLine = match.replaceFirst("name=\"" + name + "\"");
            }
            sb.append(textinLine + "\n");
        }
        fs.close();
        in.close();
        br.close();
    } catch (FileNotFoundException e) {
        logger.error(e.getMessage(), e);
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }

    try {
        FileWriter fstream = new FileWriter(f); // write file again
        BufferedWriter outobj = new BufferedWriter(fstream);
        outobj.write(sb.toString());
        outobj.close();

    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
}

From source file:mase.MaseEvolve.java

public static File writeConfig(String[] args, Map<String, String> params, File outDir,
        boolean replaceDirWildcard) throws IOException {
    File configFile = File.createTempFile("maseconfig", ".params");

    // Write the parameter map into a new file
    BufferedWriter bw = new BufferedWriter(new FileWriter(configFile));

    // Write the command line arguments in a comment
    bw.write("#");
    for (String arg : args) {
        bw.write(" " + arg);
    }/*from  www .jav  a 2  s.  co  m*/
    bw.newLine();

    // Write the parameters correctly padded
    int maxLen = -1;
    for (String str : params.keySet()) {
        maxLen = Math.max(maxLen, str.length());
    }

    for (Entry<String, String> e : params.entrySet()) {
        String value = e.getValue();
        if (value.contains("$") && replaceDirWildcard) {
            File f = new File(outDir, value.replace("$", ""));
            value = f.getAbsolutePath().replace("\\", "/");
        }
        bw.write(StringUtils.rightPad(e.getKey(), maxLen) + " = " + value);
        bw.newLine();
    }
    bw.close();

    return configFile;
}

From source file:com.sp.Parser.Utils.java

public static synchronized void Send_TCP(Socket s, String JsonFormattedResponse) throws IOException {

    BufferedWriter outToClient = new BufferedWriter(new OutputStreamWriter(s.getOutputStream(), "UTF-8"));
    outToClient.write(JsonFormattedResponse);
    outToClient.flush();/* w w w  . jav a2 s.  c  om*/
}

From source file:com.example.SampleStreamExample.java

public static void run(String consumerKey, String consumerSecret, String token, String secret)
        throws InterruptedException {
    // Create an appropriately sized blocking queue
    BlockingQueue<String> queue = new LinkedBlockingQueue<String>(10000);

    // Define our endpoint: By default, delimited=length is set (we need this for our processor)
    // and stall warnings are on.
    StatusesSampleEndpoint endpoint = new StatusesSampleEndpoint();
    endpoint.stallWarnings(false);/*from w  ww.  j av a2 s.  com*/

    File file = new File("/usr/local/Output11.txt");

    if (!file.exists()) {
        try {
            file.createNewFile();
            FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write("[");
            bw.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    Authentication auth = new OAuth1(consumerKey, consumerSecret, token, secret);
    //Authentication auth = new com.twitter.hbc.httpclient.auth.BasicAuth(username, password);

    // Create a new BasicClient. By default gzip is enabled.
    BasicClient client = new ClientBuilder().name("sampleExampleClient").hosts(Constants.STREAM_HOST)
            .endpoint(endpoint).authentication(auth).processor(new StringDelimitedProcessor(queue)).build();

    // Establish a connection
    client.connect();

    // Do whatever needs to be done with messages
    for (int msgRead = 0; msgRead < 1000; msgRead++) {
        if (client.isDone()) {
            System.out.println("Client connection closed unexpectedly: " + client.getExitEvent().getMessage());
            break;
        }

        String msg = queue.poll(5, TimeUnit.SECONDS);
        //  String Time="time",Text="Text";
        //Lang id;
        if (msg == null) {
            System.out.println("Did not receive a message in 5 seconds");
        } else {

            System.out.println(msg);
            //System.out.println("**************hahahahahahahah********************");

            try {
                FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
                BufferedWriter bw = new BufferedWriter(fw);

                if (msgRead == 999)
                    bw.write(msg);
                else
                    bw.write(msg + ",");

                bw.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            /*     JSONParser jsonParser = new JSONParser();
                   //JsonElement jsonElement = null;
                           
                   String key="";
                try {
                   //jsonElement= (JsonElement) jsonParser.parse(msg); 
                 JSONObject jsonObject = (JSONObject) jsonParser.parse(msg);
                 //JsonObject jsonObjec = jsonElement.getAsJsonObject();
                 //for(Entry<String, JsonElement> entry : jsonObjec.entrySet())
              //   {  key = entry.getKey();
                 //   if(key=="delete")
                    //      System.out.println("this comment is deleted");
              //   }   
                   //JsonElement value = entry.getValue();
                         
                 //***** printing date
              //   Time = (String) jsonObject.get("created_at");
                    System.out.println("Date of creation====: " + jsonObject.get("created_at"));
                    //******printing id
                  //   id = (Lang) jsonObject.get("id");
                 //   System.out.println("id=========: " + jsonObject.get("id"));
                    //*******text
                     //Text = (String) jsonObject.get("text");
                   //System.out.println("Text==========: " + jsonObject.get("text"));
                            
                    //************inside user************
                    JSONObject structure = (JSONObject) jsonObject.get("user");
                    System.out.println("Into user structure ,  id====: " + structure.get("id"));
                    System.out.println("Into user structure ,  name====: " + structure.get("name"));
                    System.out.println("Into user structure ,  screen_name====: " + structure.get("screen_name"));
                    System.out.println("Into user structure ,  location====: " + structure.get("location"));
                    System.out.println("Into user structure ,  description====: " + structure.get("description"));
                    System.out.println("Into user structure ,  followers====: " + structure.get("followers_count"));
                    System.out.println("Into user structure ,  friends====: " + structure.get("friends_count"));
                    System.out.println("Into user structure ,  listed====: " + structure.get("listed_count"));
                    System.out.println("Into user structure ,  favorite====: " + structure.get("favorites_count"));
                    System.out.println("Into user structure ,  status_count====: " + structure.get("status_count"));
                    System.out.println("Into user structure ,  created at====: " + structure.get("created at"));
                            
                            
                            
                         
              } catch (ParseException e) {
                 // TODO Auto-generated catch block
                 e.printStackTrace();
              }
                    
                  */
        }
    }
    FileWriter fw;
    try {
        fw = new FileWriter(file.getAbsoluteFile(), true);
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write("]");
        bw.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    client.stop();

    // Print some stats
    System.out.printf("The client read %d messages!\n", client.getStatsTracker().getNumMessages());

}

From source file:com.netflix.config.DynamicFileConfigurationTest.java

static void modifyConfigFile() {
    new Thread() {
        public void run() {
            try {
                BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(new FileOutputStream(configFile), "UTF-8"));
                writer.write("abc=-2"); // this property should fail validation but should not affect update of other properties
                writer.newLine();//  w  w w  . j ava 2 s  .  co  m
                writer.write("dprops1=" + String.valueOf(Long.MIN_VALUE));
                writer.newLine();
                writer.write("dprops2=" + String.valueOf(Double.MAX_VALUE));
                writer.newLine();
                writer.close();
                System.err.println(configFile.getPath() + " modified");
            } catch (Exception e) {
                e.printStackTrace();
                fail("Unexpected exception");
            }
        }
    }.start();
}

From source file:it.unibas.spicybenchmark.persistence.DAOLogFile.java

public static void saveLog(String log, String logFile) throws DAOException {
    BufferedWriter writer = null;
    try {//w w w. j a v  a 2s  .  c o m
        File f = new File(logFile);
        f.getParentFile().mkdirs();
        FileWriter fileWriter = new FileWriter(logFile);
        writer = new BufferedWriter(fileWriter);
        writer.write(log);
    } catch (FileNotFoundException fnfe) {
        throw new DAOException(" File not found: " + fnfe);
    } catch (IOException ioe) {
        throw new DAOException(" Error: " + ioe);
    } catch (NoSuchElementException nse) {
        throw new DAOException(" Error in file format: " + nse);
    } finally {
        try {
            if (writer != null) {
                writer.close();
            }
        } catch (IOException ioe) {
        }
    }
}