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:de.uzk.hki.da.metadata.XmpCollector.java

/**
 * Collect./*from   w  w  w.j  a  va2 s  .  c o m*/
 *
 * @param xmpFiles list of xmp files to collect
 * @param targetFile the target file
 * @throws IOException 
 */
public static void collect(WorkArea wa, List<DAFile> xmpFiles, File targetFile) throws IOException {

    Model model = ModelFactory.createDefaultModel();

    for (DAFile dafile : xmpFiles) {

        File file = wa.toFile(dafile);

        logger.debug("collecting XMP file {}", file.getAbsolutePath());

        StringWriter xmpWriter = new StringWriter();

        try {
            // preprocess xmp in order to make it RDF/XML compatible   
            BufferedReader reader = new BufferedReader(new FileReader(file));
            BufferedWriter writer = new BufferedWriter(xmpWriter);

            logger.debug("Read the xmp file...");
            String currentLine;
            while ((currentLine = reader.readLine()) != null) {
                String trimmedLine = currentLine.trim();
                if (trimmedLine.startsWith("<?xpacket"))
                    continue;
                if (trimmedLine.contains("x:xmpmeta"))
                    continue;
                writer.write(currentLine);
            }
            reader.close();
            writer.close();

        } catch (Exception e) {
            throw new RuntimeException("Unable to preprocess XMP file: " + file.getAbsolutePath(), e);
        }

        final String baseName = FilenameUtils.removeExtension(file.getName());
        String[] list = file.getParentFile().list(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                String baseName2 = FilenameUtils.removeExtension(name);
                if (baseName.equals(baseName2) && !name.toLowerCase().endsWith(".xmp"))
                    return true;
                else
                    return false;
            }
        });
        if (list.length > 1) {
            logger.warn("More than one matching file for sidecar file {}. Skipping ...", file.getName());
            continue;
        } else if (list.length < 1) {
            logger.warn("No matching file for sidecar file {}. Skipping ...", file.getName());
            continue;
        }

        logger.debug("found matching file {}", list[0]);
        // read XMP with matching file as base name
        // use "http://www.danrw.de/temp/" as a pseudo base URI in order to allow relative resource URIs
        model.read(new StringReader(xmpWriter.toString().trim().replaceFirst("^([\\W]+)<", "<")),
                "http://www.danrw.de/temp/" + list[0]);
    }
    FileOutputStream targetStream = null;
    try {
        targetStream = new FileOutputStream(targetFile);
        model.write(targetStream, "RDF/XML-ABBREV", "http://www.danrw.de/temp/");
    } catch (FileNotFoundException e) {
        throw new RuntimeException("Could not write XMP collection file: " + targetFile.getAbsolutePath());
    } finally {
        if (targetStream != null) {
            targetStream.close();
        }
    }

}

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

public void exportSpectrumFile(File saveFile, PiecewiseSpectrum spectrum) throws IOException {
    if (spectrum == null || saveFile == null) {
        logger_.warn("", "will not save spectrum csv file");
        return;/*w  ww .  j  a v  a 2 s.  c o  m*/
    }

    final UnivariateFunction intensity = spectrum.getIntensityFunction();

    BufferedWriter bout = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(saveFile)));
    try {
        bout.append("wavelength, intensity");
        bout.newLine();
        final DoubleRange range = spectrum.getValidRange();

        for (double x = range.getMinimumDouble(); x <= range.getMaximumDouble(); x += 1.0
                / EXPORT_SAMPLE_RATE) {
            double y = intensity.value(x);
            if (Double.isNaN(y)) {
                y = 0;
            }
            bout.append(Double.toString(x));
            bout.append(", ");
            bout.append(Double.toString(y));
            bout.newLine();
        }
    } finally {
        bout.close();
    }

    logger_.info("saved spectrum csv file to " + saveFile.getAbsolutePath());
}

From source file:net.duckling.ddl.util.FileUtil.java

/**
 * Brief Intro Here/*from www.j  a v a 2 s  .c  o  m*/
 * @param file ?
 * @param content ?
 * @param charset ?
 * @return ??
 */
public static boolean writeFile(File file, String content, String charset) {
    try {
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), charset));
        bw.write(content);
        bw.flush();
        bw.close();
        return true;
    } catch (IOException e) {
        return false;
    }
}

From source file:coolmap.application.io.internal.coolmapobject.InternalCoolMapObjectIO.java

/**
 * save the coolmap property to a JSON file - if exception occurs then
 * project can't be saved correctly//www  . j  ava 2  s.c  om
 *
 * @param object
 * @param objectFolder
 * @throws Exception
 */
private static void saveProperties(CoolMapObject object, TFile objectFolder) throws Exception {
    TFile propertyFile = new TFile(objectFolder.getAbsolutePath() + File.separator + IOTerm.FILE_PROPERTY);
    TFile stateFolder = new TFile(objectFolder.getAbsolutePath() + File.separator + IOTerm.DIR_STATE);

    //
    //Save coolMapBasic property
    BufferedWriter propertyWriter = new BufferedWriter(
            new OutputStreamWriter(new TFileOutputStream(propertyFile)));

    JSONObject property = new JSONObject();
    property.put(IOTerm.ATTR_ID, object.getID());
    property.put(IOTerm.ATTR_NAME, object.getName());
    CoolMapView view = object.getCoolMapView();
    property.put(IOTerm.ATTR_VIEW_ZOOM, new float[] { view.getZoomX(), view.getZoomY() });
    Point mapAnchor = object.getCoolMapView().getMapAnchor();
    property.put(IOTerm.ATTR_VIEW_ANCHOR, new int[] { mapAnchor.x, mapAnchor.y });

    CoolMapView v = object.getCoolMapView();
    property.put(IOTerm.ATTR_VIEW_MAXIMIZED, v.isMaximized());
    property.put(IOTerm.ATTR_VIEW_MINIMIZED, v.isMinimized());

    Rectangle b = v.getBounds();
    property.put(IOTerm.ATTR_VIEW_BOUNDS, new int[] { b.x, b.y, b.width, b.height });

    ArrayList<String> linkedMxIDs = new ArrayList<String>();
    List<CMatrix> linkedMxs = object.getBaseCMatrices();
    for (CMatrix mx : linkedMxs) {
        linkedMxIDs.add(mx.getID());
    }

    property.put(IOTerm.ATTR_VIEW_MATRICES, linkedMxIDs);

    if (object.getAggregator() != null) {
        property.put(IOTerm.ATTR_VIEW_AGGREGATOR_CLASS, object.getAggregator().getClass().getName());
    }

    if (object.getViewRenderer() != null) {
        property.put(IOTerm.ATTR_VIEW_RENDERER_CLASS, object.getViewRenderer().getClass().getName());
    }

    if (object.getSnippetConverter() != null) {
        property.put(IOTerm.ATTR_VIEW_SNIPPETCONVERTER_CLASS,
                object.getSnippetConverter().getClass().getName());
    }

    //Save the side panels used in CoolMapView
    boolean rowPanelVisible = object.getCoolMapView().isRowPanelsVisible();
    boolean columnPanelVisible = object.getCoolMapView().isColumnPanelsVisible();

    JSONObject rowPanelConfig = new JSONObject();
    property.put(IOTerm.ATTR_VIEW_PANEL_ROW, rowPanelConfig);

    if (rowPanelVisible) {
        rowPanelConfig.put(IOTerm.ATTR_VIEW_PANEL_CONTAINER_VISIBLE, true);
    }
    //figure out which panels are visible
    List<RowMap> rowMaps = object.getCoolMapView().getRowMaps();
    ArrayList<JSONObject> rowMapsList = new ArrayList<>(rowMaps.size());

    for (RowMap map : rowMaps) {
        JSONObject rowMapEntry = new JSONObject();
        rowMapsList.add(rowMapEntry);
        rowMapEntry.put(IOTerm.ATTR_CLASS, map.getClass().getName());

        //config
        JSONObject config = map.getCurrentState();
        if (config != null) {
            rowMapEntry.put(IOTerm.ATTR_CONFIG, config);
        }
    }

    rowPanelConfig.put(IOTerm.ATTR_VIEW_PANEL, rowMapsList);

    ///////////////////////////////////////////////
    //columnMaps
    JSONObject columnPanelConfig = new JSONObject();
    property.put(IOTerm.ATTR_VIEW_PANEL_COLUMN, columnPanelConfig);
    if (columnPanelVisible) {
        columnPanelConfig.put(IOTerm.ATTR_VIEW_PANEL_CONTAINER_VISIBLE, true);

    }

    List<ColumnMap> columnMaps = object.getCoolMapView().getColumnMaps();
    ArrayList<JSONObject> columnMapsList = new ArrayList<>(columnMaps.size());

    //
    for (ColumnMap map : columnMaps) {
        JSONObject colMapEntry = new JSONObject();
        columnMapsList.add(colMapEntry);
        colMapEntry.put(IOTerm.ATTR_CLASS, map.getClass().getName());

        //config
        JSONObject config = map.getCurrentState();
        if (config != null) {
            colMapEntry.put(IOTerm.ATTR_CONFIG, config);
        }
    }

    columnPanelConfig.put(IOTerm.ATTR_VIEW_PANEL, columnMapsList);

    //figure out which panels are visible
    propertyWriter.write(property.toString());
    propertyWriter.flush();
    propertyWriter.close();

    try {
        //Save aggregator property JSON
        if (object.getAggregator() != null) {
            JSONObject aggregatorProperty = object.getAggregator().getCurrentState();
            if (aggregatorProperty != null) {
                BufferedWriter aggregatorWriter = new BufferedWriter(
                        new OutputStreamWriter(new TFileOutputStream(objectFolder.getAbsolutePath()
                                + File.separator + IOTerm.FILE_PROPERTY_RENDERER)));

                aggregatorWriter.write(aggregatorProperty.toString());

                aggregatorWriter.flush();
                aggregatorWriter.close();
            }
        }
    } catch (Exception e) {
        //can still continue, just the aggreat
        System.err.println("Aggregator state saving error");
    }

    //Save renderer property JSON
    try {
        if (object.getViewRenderer() != null) {
            JSONObject rendererProperty = object.getViewRenderer().getCurrentState();
            if (rendererProperty != null) {

                BufferedWriter viewRendererWriter = new BufferedWriter(
                        new OutputStreamWriter(new TFileOutputStream(objectFolder.getAbsolutePath()
                                + File.separator + IOTerm.FILE_PROPERTY_RENDERER)));

                viewRendererWriter.write(rendererProperty.toString());

                viewRendererWriter.flush();
                viewRendererWriter.close();
            }
        }
    } catch (Exception e) {
        System.err.println("Renderer state saving error");
    }

    //Save snippet property JSON
    try {
        if (object.getSnippetConverter() != null) {
            JSONObject snippetProperty = object.getAggregator().getCurrentState();
            if (snippetProperty != null) {
                BufferedWriter snippetWriter = new BufferedWriter(new OutputStreamWriter(new TFileOutputStream(
                        objectFolder.getAbsolutePath() + File.separator + IOTerm.FILE_PROPERTY_RENDERER)));

                snippetWriter.write(snippetProperty.toString());

                snippetWriter.flush();
                snippetWriter.close();
            }

        }
    } catch (Exception e) {
        System.out.println("Snippet state saving erorr");
    }

}

From source file:com.employee.scheduler.common.persistence.AbstractTxtSolutionExporter.java

public void writeSolution(Solution solution, File outputFile) {
    BufferedWriter bufferedWriter = null;
    try {// www .  j  a v  a2 s .com
        bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), "UTF-8"));
        TxtOutputBuilder txtOutputBuilder = createTxtOutputBuilder();
        txtOutputBuilder.setBufferedWriter(bufferedWriter);
        txtOutputBuilder.setSolution(solution);
        txtOutputBuilder.writeSolution();
    } catch (IOException e) {
        throw new IllegalArgumentException("Could not write the file (" + outputFile.getName() + ").", e);
    } finally {
        IOUtils.closeQuietly(bufferedWriter);
    }
    logger.info("Exported: {}", outputFile);
}

From source file:matrix.CreateTextMatrix.java

public void textMatrix()
        throws UnsupportedEncodingException, FileNotFoundException, IOException, ParseException {

    CosSim cossim = new CosSim();
    JSONParser jParser = new JSONParser();
    BufferedReader in = new BufferedReader(new InputStreamReader(
            new FileInputStream("/Users/nSabri/Desktop/tweetMatris/userTweets.json"), "ISO-8859-9"));
    JSONArray a = (JSONArray) jParser.parse(in);
    File fout = new File("/Users/nSabri/Desktop/tweetMatris.csv");
    FileOutputStream fos = new FileOutputStream(fout);
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));

    for (int i = 0; i < 1000; i++) {

        for (int j = 0; j < 1000; j++) {

            JSONObject tweet1 = (JSONObject) a.get(i);
            JSONObject tweet2 = (JSONObject) a.get(j);
            String tweetText1 = tweet1.get("tweets").toString();
            String tweetText2 = tweet2.get("tweets").toString();

            double CosSimValue = cossim.Cosine_Similarity_Score(tweetText1, tweetText2);
            CosSimValue = Double.parseDouble(new DecimalFormat("##.###").format(CosSimValue));
            bw.write(Double.toString(CosSimValue) + ", ");

        }/*from   w  w w .  j  av  a 2 s  .  c  om*/
        bw.newLine();
    }
    bw.close();

}

From source file:edu.usu.sdl.openstorefront.report.generator.HtmlGenerator.java

@Override
public void init() {
    Objects.requireNonNull(report, "The generator requires the report to exist.");
    Objects.requireNonNull(report.getReportId(), "The report id is required.");
    try {//from  ww  w  . ja  va 2  s.  co m
        writer = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(report.pathToReport().toFile())));
        writer.append("<html><body style='padding: 20px'>");
    } catch (IOException ex) {
        throw new OpenStorefrontRuntimeException("Unable to open file to write report.",
                "Check file system permissions", ex);
    }
}

From source file:matrix.CreateUrlMatrix.java

public void urlMatrix()
        throws UnsupportedEncodingException, FileNotFoundException, IOException, ParseException {

    CosSim cossim = new CosSim();
    JSONParser jParser = new JSONParser();
    BufferedReader in = new BufferedReader(new InputStreamReader(
            new FileInputStream("/Users/nSabri/Desktop/tweetMatris/userTweetsUrls.json"), "ISO-8859-9"));
    JSONArray a = (JSONArray) jParser.parse(in);
    File fout = new File("/Users/nSabri/Desktop/urlMatris.csv");
    FileOutputStream fos = new FileOutputStream(fout);
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));

    for (int i = 0; i < a.size(); i++) {

        for (int j = 0; j < a.size(); j++) {

            JSONObject tweet1 = (JSONObject) a.get(i);
            JSONObject tweet2 = (JSONObject) a.get(j);
            String tweetUrl1 = tweet1.get("title").toString() + tweet1.get("meta").toString();
            System.out.println(tweetUrl1);
            String tweetUrl2 = tweet2.get("title").toString() + tweet1.get("meta").toString();
            System.out.println(tweetUrl2);

            double CosSimValue = cossim.Cosine_Similarity_Score(tweetUrl1, tweetUrl2);
            CosSimValue = Double.parseDouble(new DecimalFormat("##.###").format(CosSimValue));
            bw.write(Double.toString(CosSimValue) + ", ");

        }//from w  w  w .  j  ava2  s .co  m
        bw.newLine();
    }
    bw.close();

}

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   ww w .j ava  2  s . c om

    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.linkedin.pinot.tools.admin.command.AbstractBaseAdminCommand.java

public static String sendPostRequest(String urlString, String payload)
        throws UnsupportedEncodingException, IOException, JSONException {
    final URL url = new URL(urlString);
    final URLConnection conn = url.openConnection();

    conn.setDoOutput(true);//from  www  .j  a  va 2 s . c o m
    final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));

    writer.write(payload, 0, payload.length());
    writer.flush();

    final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
    final StringBuilder sb = new StringBuilder();
    String line = null;

    while ((line = reader.readLine()) != null) {
        sb.append(line);
    }

    return sb.toString();
}