Example usage for java.io FileWriter append

List of usage examples for java.io FileWriter append

Introduction

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

Prototype

@Override
    public Writer append(CharSequence csq) throws IOException 

Source Link

Usage

From source file:es.csic.iiia.planes.cli.Cli.java

/**
 * Parse the provided list of arguments according to the program's options.
 * //ww  w  . j ava 2  s  .  c o  m
 * @param in_args
 *            list of input arguments.
 * @return a configuration object set according to the input options.
 */
private static Configuration parseOptions(String[] in_args) {
    CommandLineParser parser = new PosixParser();
    CommandLine line = null;
    Properties settings = loadDefaultSettings();

    try {
        line = parser.parse(options, in_args);
    } catch (ParseException ex) {
        Logger.getLogger(Cli.class.getName()).log(Level.SEVERE, ex.getLocalizedMessage(), ex);
        showHelp();
    }

    if (line.hasOption('h')) {
        showHelp();
    }

    if (line.hasOption('d')) {
        dumpSettings();
    }

    if (line.hasOption('s')) {
        String fname = line.getOptionValue('s');
        try {
            settings.load(new FileReader(fname));
        } catch (IOException ex) {
            throw new IllegalArgumentException("Unable to load the settings file \"" + fname + "\"");
        }
    }

    // Apply overrides
    settings.setProperty("gui", String.valueOf(line.hasOption('g')));
    settings.setProperty("quiet", String.valueOf(line.hasOption('q')));
    Properties overrides = line.getOptionProperties("o");
    settings.putAll(overrides);

    String[] args = line.getArgs();
    if (args.length < 1) {
        showHelp();
    }
    settings.setProperty("problem", args[0]);

    Configuration c = new Configuration(settings);
    System.out.println(c.toString());
    /**
     * Modified by Guillermo B. Print settings to a result file, titled
     * "results.txt"
     */
    try {
        FileWriter fw = new FileWriter("results.txt", true);
        BufferedWriter bw = new BufferedWriter(fw);
        PrintWriter out = new PrintWriter(bw);
        String[] results = c.toString().split("\n");
        // out.println(results[8]);

        for (String s : results) {
            out.println(s);

        }
        // out.println(results[2]);
        // out.println(results[8]);
        out.close();
    } catch (IOException e) {
    }

    /**
     * Modified by Ebtesam Save settings to a .csv file, titled
     * "resultsCSV.csv"
     */

    try {
        FileWriter writer = new FileWriter("resultsCSV.csv", true);
        FileReader reader = new FileReader("resultsCSV.csv");

        String header = "SAR Strategy,# of Searcher UAVs,# of Survivors,"
                + "# of Survivors rescued,Min.Time needed to rescue Survivors,Mean. Time needed to rescue Survivors,Max. Time needed to rescue Survivors,"
                + "# of Survivors found,Min. Time needed to find Survivors,Mean Time needed to find Survivors,Max. Time needed to find Survivors,"
                + "Running Time of Simulation\n";
        if (reader.read() == -1) {
            writer.append(header);
            writer.append("\n");
        }
        reader.close();
        String[] results = c.toString().split("\n");
        writer.append(results[2].substring(10));
        writer.append(",");
        writer.append(results[20].substring(11));
        writer.append(",");
        writer.append(results[30].substring(18));
        writer.write(",");
        writer.close();
    } catch (IOException e) {
    }

    if (line.hasOption('t')) {
        System.exit(0);
    }
    return c;
}

From source file:org.apache.flume.sink.kite.TestDatasetSink.java

@BeforeClass
public static void saveSchema() throws IOException {
    oldTestBuildDataProp = System.getProperty(TEST_BUILD_DATA_KEY);
    System.setProperty(TEST_BUILD_DATA_KEY, DFS_DIR);
    FileWriter schema = new FileWriter(SCHEMA_FILE);
    schema.append(RECORD_SCHEMA.toString());
    schema.close();// www . j  ava 2 s. co  m
}

From source file:org.metawatch.manager.Monitors.java

public static JSONObject getJSONfromURL(String url) {

    //initialize/*  ww  w.  j ava2 s  .c om*/
    InputStream is = null;
    String result = "";
    JSONObject jArray = null;

    //http post
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();

    } catch (Exception e) {
        if (Preferences.logging)
            Log.e(MetaWatch.TAG, "Error in http connection " + e.toString());
    }

    //convert response to string
    if (is != null) {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            result = sb.toString();
        } catch (Exception e) {
            if (Preferences.logging)
                Log.e(MetaWatch.TAG, "Error converting result " + e.toString());
        }

        // dump to sdcard for debugging
        File sdCard = Environment.getExternalStorageDirectory();
        File file = new File(sdCard, "weather.json");

        try {
            FileWriter writer = new FileWriter(file);
            writer.append(result);
            writer.flush();
            writer.close();
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // try parse the string to a JSON object
        try {
            jArray = new JSONObject(result);
        } catch (JSONException e) {
            if (Preferences.logging)
                Log.e(MetaWatch.TAG, "Error parsing data " + e.toString());
        }
    }
    return jArray;
}

From source file:au.org.ala.layers.grid.GridClassBuilder.java

public static HashMap<Integer, GridClass> buildFromGrid(String filePath) throws IOException {
    File wktDir = new File(filePath);
    wktDir.mkdirs();/*  w w w.  j a v a 2 s . co  m*/

    int[] wktMap = null;

    //track values for the SLD
    ArrayList<Integer> maxValues = new ArrayList<Integer>();
    ArrayList<String> labels = new ArrayList<String>();

    HashMap<Integer, GridClass> classes = new HashMap<Integer, GridClass>();
    Properties p = new Properties();
    p.load(new FileReader(filePath + ".txt"));

    boolean mergeProperties = false;

    Map<String, Set<Integer>> groupedKeys = new HashMap<String, Set<Integer>>();
    Map<Integer, Integer> translateKeys = new HashMap<Integer, Integer>();
    Map<String, Integer> translateValues = new HashMap<String, Integer>();
    ArrayList<Integer> keys = new ArrayList<Integer>();
    for (String key : p.stringPropertyNames()) {
        try {
            int k = Integer.parseInt(key);
            keys.add(k);

            //grouping of property file keys by value
            String value = p.getProperty(key);
            Set<Integer> klist = groupedKeys.get(value);
            if (klist == null)
                klist = new HashSet<Integer>();
            else
                mergeProperties = true;
            klist.add(k);
            groupedKeys.put(value, klist);

            if (!translateValues.containsKey(value))
                translateValues.put(value, translateValues.size() + 1);
            translateKeys.put(k, translateValues.get(value));

        } catch (NumberFormatException e) {
            logger.info("Excluding shape key '" + key + "'");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    java.util.Collections.sort(keys);

    Grid g = new Grid(filePath);
    boolean generateWkt = false; //((long) g.nrows) * ((long) g.ncols) < (long) Integer.MAX_VALUE;

    if (mergeProperties) {
        g.replaceValues(translateKeys);

        if (!new File(filePath + ".txt.old").exists())
            FileUtils.moveFile(new File(filePath + ".txt"), new File(filePath + ".txt.old"));

        StringBuilder sb = new StringBuilder();
        for (String value : translateValues.keySet()) {
            sb.append(translateValues.get(value)).append("=").append(value).append('\n');
        }
        FileUtils.writeStringToFile(new File(filePath + ".txt"), sb.toString());

        return buildFromGrid(filePath);
    }

    if (generateWkt) {
        for (String name : groupedKeys.keySet()) {
            try {
                Set<Integer> klist = groupedKeys.get(name);

                String key = klist.iterator().next().toString();
                int k = Integer.parseInt(key);

                GridClass gc = new GridClass();
                gc.setName(name);
                gc.setId(k);

                if (klist.size() == 1)
                    klist = null;

                logger.info("getting wkt for " + filePath + " > " + key);

                Map wktIndexed = Envelope.getGridSingleLayerEnvelopeAsWktIndexed(
                        filePath + "," + key + "," + key, klist, wktMap);

                //write class wkt
                File zipFile = new File(filePath + File.separator + key + ".wkt.zip");
                ZipOutputStream zos = null;
                try {
                    zos = new ZipOutputStream(new FileOutputStream(zipFile));
                    zos.putNextEntry(new ZipEntry(key + ".wkt"));
                    zos.write(((String) wktIndexed.get("wkt")).getBytes());
                    zos.flush();
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                } finally {
                    if (zos != null) {
                        try {
                            zos.close();
                        } catch (Exception e) {
                            logger.error(e.getMessage(), e);
                        }
                    }
                }
                BufferedOutputStream bos = null;
                try {
                    bos = new BufferedOutputStream(
                            new FileOutputStream(filePath + File.separator + key + ".wkt"));
                    bos.write(((String) wktIndexed.get("wkt")).getBytes());
                    bos.flush();
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                } finally {
                    if (bos != null) {
                        try {
                            bos.close();
                        } catch (Exception e) {
                            logger.error(e.getMessage(), e);
                        }
                    }
                }
                logger.info("wkt written to file");
                gc.setArea_km(SpatialUtil.calculateArea((String) wktIndexed.get("wkt")) / 1000.0 / 1000.0);

                //store map
                wktMap = (int[]) wktIndexed.get("map");

                //write wkt index
                FileWriter fw = null;
                try {
                    fw = new FileWriter(filePath + File.separator + key + ".wkt.index");
                    fw.append((String) wktIndexed.get("index"));
                    fw.flush();
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                } finally {
                    if (fw != null) {
                        try {
                            fw.close();
                        } catch (Exception e) {
                            logger.error(e.getMessage(), e);
                        }
                    }
                }
                //write wkt index a binary, include extents (minx, miny, maxx, maxy) and area (sq km)
                int minPolygonNumber = 0;
                int maxPolygonNumber = 0;

                RandomAccessFile raf = null;
                try {
                    raf = new RandomAccessFile(filePath + File.separator + key + ".wkt.index.dat", "rw");

                    String[] index = ((String) wktIndexed.get("index")).split("\n");

                    for (int i = 0; i < index.length; i++) {
                        if (index[i].length() > 1) {
                            String[] cells = index[i].split(",");
                            int polygonNumber = Integer.parseInt(cells[0]);
                            raf.writeInt(polygonNumber); //polygon number
                            int polygonStart = Integer.parseInt(cells[1]);
                            raf.writeInt(polygonStart); //character offset

                            if (i == 0) {
                                minPolygonNumber = polygonNumber;
                            } else if (i == index.length - 1) {
                                maxPolygonNumber = polygonNumber;
                            }
                        }
                    }
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                } finally {
                    if (raf != null) {
                        try {
                            raf.close();
                        } catch (Exception e) {
                            logger.error(e.getMessage(), e);
                        }
                    }
                }

                //for SLD
                maxValues.add(gc.getMaxShapeIdx());
                labels.add(name.replace("\"", "'"));
                gc.setMinShapeIdx(minPolygonNumber);
                gc.setMaxShapeIdx(maxPolygonNumber);

                logger.info("getting multipolygon for " + filePath + " > " + key);
                MultiPolygon mp = Envelope.getGridEnvelopeAsMultiPolygon(filePath + "," + key + "," + key);
                gc.setBbox(mp.getEnvelope().toText().replace(" (", "(").replace(", ", ","));

                classes.put(k, gc);

                try {
                    //write class kml
                    zos = null;
                    try {
                        zos = new ZipOutputStream(
                                new FileOutputStream(filePath + File.separator + key + ".kml.zip"));

                        zos.putNextEntry(new ZipEntry(key + ".kml"));
                        Encoder encoder = new Encoder(new KMLConfiguration());
                        encoder.setIndenting(true);
                        encoder.encode(mp, KML.Geometry, zos);
                        zos.flush();
                    } catch (Exception e) {
                        logger.error(e.getMessage(), e);
                    } finally {
                        if (zos != null) {
                            try {
                                zos.close();
                            } catch (Exception e) {
                                logger.error(e.getMessage(), e);
                            }
                        }
                    }
                    logger.info("kml written to file");

                    final SimpleFeatureType TYPE = DataUtilities.createType("class",
                            "the_geom:MultiPolygon,id:Integer,name:String");
                    FeatureJSON fjson = new FeatureJSON();
                    SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(TYPE);
                    SimpleFeature sf = featureBuilder.buildFeature(null);

                    //write class geojson
                    zos = null;
                    try {
                        zos = new ZipOutputStream(
                                new FileOutputStream(filePath + File.separator + key + ".geojson.zip"));
                        zos.putNextEntry(new ZipEntry(key + ".geojson"));
                        featureBuilder.add(mp);
                        featureBuilder.add(k);
                        featureBuilder.add(name);

                        fjson.writeFeature(sf, zos);
                        zos.flush();
                    } catch (Exception e) {
                        logger.error(e.getMessage(), e);
                    } finally {
                        if (zos != null) {
                            try {
                                zos.close();
                            } catch (Exception e) {
                                logger.error(e.getMessage(), e);
                            }
                        }
                    }
                    logger.info("geojson written to file");

                    //write class shape file
                    File newFile = new File(filePath + File.separator + key + ".shp");
                    ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();
                    Map<String, Serializable> params = new HashMap<String, Serializable>();
                    params.put("url", newFile.toURI().toURL());
                    params.put("create spatial index", Boolean.FALSE);
                    ShapefileDataStore newDataStore = null;
                    try {
                        newDataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params);
                        newDataStore.createSchema(TYPE);
                        newDataStore.forceSchemaCRS(DefaultGeographicCRS.WGS84);
                        Transaction transaction = new DefaultTransaction("create");
                        String typeName = newDataStore.getTypeNames()[0];
                        SimpleFeatureSource featureSource = newDataStore.getFeatureSource(typeName);
                        SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;
                        featureStore.setTransaction(transaction);
                        List<SimpleFeature> features = new ArrayList<SimpleFeature>();

                        DefaultFeatureCollection collection = new DefaultFeatureCollection();
                        collection.addAll(features);
                        featureStore.setTransaction(transaction);

                        features.add(sf);
                        featureStore.addFeatures(collection);
                        transaction.commit();
                        transaction.close();
                    } catch (Exception e) {
                        logger.error(e.getMessage(), e);
                    } finally {
                        if (newDataStore != null) {
                            try {
                                newDataStore.dispose();
                            } catch (Exception e) {
                                logger.error(e.getMessage(), e);
                            }
                        }
                    }

                    zos = null;
                    try {
                        zos = new ZipOutputStream(
                                new FileOutputStream(filePath + File.separator + key + ".shp.zip"));
                        //add .dbf .shp .shx .prj
                        String[] exts = { ".dbf", ".shp", ".shx", ".prj" };
                        for (String ext : exts) {
                            zos.putNextEntry(new ZipEntry(key + ext));
                            FileInputStream fis = null;
                            try {
                                fis = new FileInputStream(filePath + File.separator + key + ext);
                                byte[] buffer = new byte[1024];
                                int size;
                                while ((size = fis.read(buffer)) > 0) {
                                    zos.write(buffer, 0, size);
                                }
                            } catch (Exception e) {
                                logger.error(e.getMessage(), e);
                            } finally {
                                if (fis != null) {
                                    try {
                                        fis.close();
                                    } catch (Exception e) {
                                        logger.error(e.getMessage(), e);
                                    }
                                }
                            }
                            //remove unzipped files
                            new File(filePath + File.separator + key + ext).delete();
                        }
                        zos.flush();
                    } catch (Exception e) {
                        logger.error(e.getMessage(), e);
                    } finally {
                        if (zos != null) {
                            try {
                                zos.close();
                            } catch (Exception e) {
                                logger.error(e.getMessage(), e);
                            }
                        }
                    }
                    logger.info("shape file written to zip");
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }

        //write polygon mapping
        g.writeGrid(filePath + File.separator + "polygons", wktMap, g.xmin, g.ymin, g.xmax, g.ymax, g.xres,
                g.yres, g.nrows, g.ncols);

        //copy the header file to get it exactly the same, but change the data type
        copyHeaderAsInt(filePath + ".grd", filePath + File.separator + "polygons.grd");
    } else {
        //build classes without generating polygons
        Map<Float, float[]> info = new HashMap<Float, float[]>();
        for (int j = 0; j < keys.size(); j++) {
            info.put(keys.get(j).floatValue(), new float[] { 0, Float.NaN, Float.NaN, Float.NaN, Float.NaN });
        }

        g.getClassInfo(info);

        for (int j = 0; j < keys.size(); j++) {
            int k = keys.get(j);
            String key = String.valueOf(k);

            String name = p.getProperty(key);

            GridClass gc = new GridClass();
            gc.setName(name);
            gc.setId(k);

            //for SLD
            maxValues.add(Integer.valueOf(key));
            labels.add(name.replace("\"", "'"));
            gc.setMinShapeIdx(Integer.valueOf(key));
            gc.setMaxShapeIdx(Integer.valueOf(key));

            float[] stats = info.get(keys.get(j).floatValue());

            //only include if area > 0
            if (stats[0] > 0) {
                gc.setBbox("POLYGON((" + stats[1] + " " + stats[2] + "," + stats[1] + " " + stats[4] + ","
                        + stats[3] + " " + stats[4] + "," + stats[3] + " " + stats[2] + "," + stats[1] + " "
                        + stats[2] + "))");

                gc.setArea_km((double) stats[0]);
                classes.put(k, gc);
            }
        }
    }

    //write sld
    exportSLD(filePath + File.separator + "polygons.sld", new File(filePath + ".txt").getName(), maxValues,
            labels);

    writeProjectionFile(filePath + File.separator + "polygons.prj");

    //write .classes.json
    ObjectMapper mapper = new ObjectMapper();
    mapper.writeValue(new File(filePath + ".classes.json"), classes);

    return classes;
}

From source file:de.hstsoft.sdeep.Configuration.java

@SuppressWarnings("unchecked")
public void save() {
    JSONObject jsonObject = new JSONObject();

    jsonObject.put(PREF_SAVEGAME_PATH, saveGamePath);
    jsonObject.put(PREF_AUTOREFRESH, autorefresh);

    try {/*  ww w .ja  v  a  2 s  .  c  o m*/
        String jsonString = jsonObject.toJSONString();
        FileWriter fileWriter = new FileWriter(configFile);
        fileWriter.append(jsonString);
        fileWriter.flush();
        fileWriter.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.servioticy.dispatcher.bolts.BenchmarkBolt.java

@Override
public void execute(Tuple input) {
    String suDoc = input.getStringByField("su");
    Long stopTS = input.getLongByField("stopts") == null ? System.currentTimeMillis()
            : input.getLongByField("stopts");
    String reason = input.getStringByField("reason") == null ? "timeout" : input.getStringByField("reason");

    SensorUpdate su;/*from   ww w  . j a  v a 2 s. co  m*/
    try {
        su = this.mapper.readValue(suDoc, SensorUpdate.class);

        int chainSize = su.getPathTimestamps() == null ? 0 : su.getPathTimestamps().size();

        String csvLine = Long.toHexString(su.getOriginId()) + "," + su.getLastUpdate() + "," + stopTS + ","
                + reason + "," + chainSize;
        for (int i = 0; i < chainSize; i++) {
            csvLine += ",";
            csvLine += su.getPathTimestamps().get(i) + ",";
            csvLine += su.getTriggerPath().get(i).get(0) + "," + su.getTriggerPath().get(i).get(1);
        }

        File file = new File(dc.benchResultsDir + "/" + context.getThisTaskId() + ".csv");
        file.createNewFile();
        FileWriter writer = new FileWriter(file, true);
        writer.append(csvLine + "\n");
        writer.flush();
        writer.close();
    } catch (Exception e) {
        // TODO Log the error
        e.printStackTrace();
        collector.ack(input);
        return;
    }
    collector.ack(input);
}

From source file:de.hstsoft.sdeep.NoteManager.java

@SuppressWarnings("unchecked")
private void saveNotes() {
    JSONObject envelope = new JSONObject();
    envelope.put("version", VERSION);

    JSONArray jsonArray = new JSONArray();
    for (Note n : notes) {
        jsonArray.add(n.toJson());//from   w  w w  .  j av a2  s.c o  m
    }

    envelope.put("notes", jsonArray);

    try {
        File file = new File(directory + FILENAME);
        FileWriter fileWriter = new FileWriter(file);
        fileWriter.append(envelope.toJSONString());
        fileWriter.flush();
        fileWriter.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:org.apache.jackrabbit.oak.spi.blob.split.BlobIdSet.java

private void addToStore(String blobId) throws IOException {
    FileWriter writer = new FileWriter(store.getPath(), true);
    try {//from w  w w.j ava2 s  .co m
        writer.append(blobId).append('\n');
    } finally {
        writer.close();
    }
}

From source file:com.ontotext.s4.multiThreadRequest.thread.ThreadClient.java

public void saveFile(String text, File file) throws IOException {
    FileWriter fileWriter = new FileWriter(file);
    fileWriter.append(text);
    fileWriter.close();//from w  w  w  .jav a 2  s .c o  m

}

From source file:com.springsource.hq.plugin.tcserver.plugin.serverconfig.FileUtilityTest.java

@Before
public void setup() throws IOException {
    LOGGER.debug("TEMP_DIR = " + TEMP_DIR);
    File sampleDirectory = new File(TEMP_DIR + "/config");
    LOGGER.debug("Temp dir/config created: " + sampleDirectory.mkdir());
    File sampleFile1 = new File(sampleDirectory.getAbsolutePath() + "/tempfile1.tmp");
    sampleFile1.createNewFile();// www .  ja v  a2  s  .  c  o m
    LOGGER.debug("SampleFile1 - " + sampleFile1.getAbsolutePath() + " - created: " + sampleFile1.isFile());
    FileWriter fileWriter = new FileWriter(sampleFile1);
    fileWriter.append(FILE1_TEXT);
    fileWriter.close();
    File sampleFile2 = new File(sampleDirectory.getAbsolutePath() + "/tempfile2.tmp");
    sampleFile2.createNewFile();
    LOGGER.debug("SampleFile2 - " + sampleFile2.getAbsolutePath() + " - created: " + sampleFile1.isFile());
    fileWriter = new FileWriter(sampleFile2);
    fileWriter.append(FILE2_TEXT);
    fileWriter.close();
}