Example usage for java.io FileWriter FileWriter

List of usage examples for java.io FileWriter FileWriter

Introduction

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

Prototype

public FileWriter(File file, Charset charset) throws IOException 

Source Link

Document

Constructs a FileWriter given the File to write and java.nio.charset.Charset charset .

Usage

From source file:com.dongli.model.MyJSONData.java

public static String createObject(MyJSONObject mjo) throws MyRESTException {

    // generate uid for this object
    String uid = UIDGenerator.getUID();
    mjo.setUID(uid);//from  w  w w  .  ja  va  2s. c om

    // tmp path of data file to store this object. The file will to sent to S3 later.
    String path = "/tmp/" + uid;

    try {
        FileWriter fw = new FileWriter(path, false);
        PrintWriter pw = new PrintWriter(fw);
        pw.println(mjo.toString());
        pw.close();
        fw.close();
    } catch (IOException e) {
        // e.printStackTrace();
        // failed to create the new object
        File nf = new File(path);
        nf.delete();
        throw new MyRESTException("Failed to create the object " + uid + ".");
    }

    // create the new object on AWS S3 
    try {
        File uploadFile = new File(path);
        MyAWSStorage.getInstance().s3client
                .putObject(new PutObjectRequest(MyConfiguration.getInstance().bucket, uid, uploadFile));
    } catch (AmazonServiceException ase) {
        throw new MyRESTException("Failed to create the object " + uid + ".");
    } catch (AmazonClientException ace) {
        throw new MyRESTException("Failed to create the object " + uid + ".");
    }

    return uid;
}

From source file:gov.nih.nci.ncicb.tcga.dcc.qclive.common.logging.FileLoggerDestination.java

protected void log(final String message) throws LoggerException {
    try {//from   w w  w .  j  a  v  a2s.co  m
        if (this.writer == null) {
            //noinspection IOResourceOpenedButNotSafelyClosed
            this.writer = new PrintWriter(new BufferedWriter(new FileWriter(filename, append)));
        }
        writer.append(message);
        writer.flush();
    } catch (IOException ioe) {
        throw new LoggerException(ioe);
    } finally {
        IOUtils.closeQuietly(writer);
        this.writer = null;
    }
}

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);//  w w w. j  av  a  2s. co  m

    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.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. j a v  a 2  s. c o m
        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:Main.java

public static boolean writeFile(String filePath, List<String> contentList, boolean append) {
    if (contentList == null || contentList.size() < 1) {
        return false;
    }// w  ww . j  a v a 2 s. c om

    FileWriter fileWriter = null;
    try {
        makeDirs(filePath);
        fileWriter = new FileWriter(filePath, append);
        int i = 0;
        for (String line : contentList) {
            if (i++ > 0) {
                fileWriter.write("\r\n");
            }
            fileWriter.write(line);
        }
        fileWriter.close();
        return true;
    } catch (IOException e) {
        throw new RuntimeException("IOException occurred. ", e);
    } finally {
        if (fileWriter != null) {
            try {
                fileWriter.close();
            } catch (IOException e) {
                throw new RuntimeException("IOException occurred. ", e);
            }
        }
    }
}

From source file:com.espe.distribuidas.pmaldito.servidorbdd.operaciones.Archivo.java

/**
 * Permite insertar registros en una tabla
 *
 * @param string/*from ww  w .j  a  v a  2  s.c om*/
 * @param archivo
 */
@SuppressWarnings("ConvertToTryWithResources")
public static void insertar(String string, File archivo) {

    try {
        FileWriter fw = new FileWriter(archivo, true);
        fw.write(string + "\n");
        fw.close();
    } catch (IOException e) {
        System.err.println(e);
    }
}

From source file:net.genesishub.gFeatures.Plus.Skript.SkriptManager.java

public void Enable(Extension s, String packages) throws IOException {
    try {/*from   w  w  w .ja  va2 s.  c  o m*/
        Reader paramReader = new InputStreamReader(getClass().getResourceAsStream(
                "/net/genesishub/gFeatures/Plus/Skript/" + packages + "/" + s.getName() + ".sk"));
        StringWriter writer = new StringWriter();
        IOUtils.copy(paramReader, writer);
        String theString = writer.toString();
        File f = new File("plugins/Skript/scripts/" + s.toString() + ".sk");
        f.createNewFile();
        BufferedWriter bw = new BufferedWriter(new FileWriter(f, true));
        bw.write(theString);
        bw.close();
    } catch (Exception E) {
    }
}

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();// w w w  .ja v a  2 s .c om
    }
    outputFile.createNewFile();
    FileWriter out = new FileWriter(outputFilePath, true);
    bufferWriter = new BufferedWriter(out);
    printer = new CSVPrinter(bufferWriter, format);
}