Example usage for java.io FileWriter flush

List of usage examples for java.io FileWriter flush

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes the stream.

Usage

From source file:gov.nasa.jpl.memex.pooledtimeseries.PoT.java

private static void writeSimilarityToJSONFile(ArrayList<Path> files, double[][] similarities) {
      JSONObject root_json_obj = new JSONObject();

      for (int i = 0; i < similarities.length; i++) {
          JSONObject fileJsonObj = new JSONObject();

          for (int j = 0; j < similarities[0].length; j++) {
              fileJsonObj.put(files.get(j).getFileName(), similarities[i][j]);
          }/*from  w  w  w .  j  a v a2  s  .co  m*/

          root_json_obj.put(files.get(i).getFileName(), fileJsonObj);
      }

      try {
          outputFile = outputFile.substring(0, outputFile.lastIndexOf('.')) + ".json";
          FileWriter file = new FileWriter(outputFile);
          file.write(root_json_obj.toJSONString());
          file.flush();
          file.close();
      } catch (IOException e) {
          e.printStackTrace();
      }
  }

From source file:com.bigtester.ate.tcg.controller.TrainingFileDB.java

/**
 * Write cache csv file./*from ww w  . j  a va  2  s.c o  m*/
 *
 * @param absoluteCacheFilePath
 *            the absolute cache file path
 * @param beginningComments
 *            the beginning comments
 * @param endingComments
 *            the ending comments
 * @param trainedRecords
 *            the trained records
 * @param append
 *            the append
 * @throws IOException
 */
public static void writeCacheCsvFile(String absoluteCacheFilePath, String beginningComments,
        String endingComments, List<UserInputTrainingRecord> trainedRecords, boolean append)
        throws IOException {
    // Create new students objects

    FileWriter fileWriter = null;// NOPMD

    CSVPrinter csvFilePrinter = null;// NOPMD

    // Create the CSVFormat object with "\n" as a record delimiter
    CSVFormat csvFileFormat = getCSVFormat();
    try {
        if (trainedRecords.isEmpty()) {
            fileWriter = new FileWriter(absoluteCacheFilePath, append);

            // initialize CSVPrinter object
            csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);

            // Write a new student object list to the CSV file
            csvFilePrinter.printComment(beginningComments);
            csvFilePrinter.printComment(endingComments);

            fileWriter.flush();
            fileWriter.close();
            csvFilePrinter.close();
            return;
        }

        // initialize FileWriter object
        fileWriter = new FileWriter(absoluteCacheFilePath, append);

        // initialize CSVPrinter object
        csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);

        // Write a new student object list to the CSV file
        csvFilePrinter.printComment(beginningComments);
        for (UserInputTrainingRecord student : trainedRecords) {
            List<String> studentDataRecord = new ArrayList<String>();
            studentDataRecord.add(student.getInputLabelName());
            studentDataRecord.add(student.getInputMLHtmlCode());

            csvFilePrinter.printRecord(studentDataRecord);
        }
        csvFilePrinter.printComment(endingComments);
        // System.out.println("CSV file was created successfully !!!");

    } catch (Exception e) {// NOPMD
        throw new IOException("Error in CsvFileWriter !!!");// NOPMD
        // e.printStackTrace();
    } finally { //NOPMD
        try {
            if (null != fileWriter) {
                fileWriter.flush();
                fileWriter.close();
            }
            if (null != csvFilePrinter)
                csvFilePrinter.close();
        } catch (IOException e) {//NOPMD
            //System.out
            throw new IOException("Error while flushing/closing fileWriter/csvPrinter !!!");//NOPMD
            //e.printStackTrace();
        }
    }
}

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

public static JSONObject getJSONfromURL(String url) {

    //initialize//from   w  w  w . j a  v  a  2 s.  c o m
    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

private static void copyHeaderAsInt(String src, String dst) {
    BufferedReader br = null;/*from ww w . ja  v  a  2s .  c  om*/
    FileWriter fw = null;
    try {
        br = new BufferedReader(new FileReader(src));
        fw = new FileWriter(dst);
        String line;
        while ((line = br.readLine()) != null) {
            if (line.startsWith("DataType=")) {
                fw.write("DataType=INT\n");
            } else {
                fw.write(line);
                fw.write("\n");
            }
        }
        fw.flush();
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
        if (fw != null) {
            try {
                fw.close();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    }
}

From source file:fr.cls.atoll.motu.processor.wps.TestServiceMetadata.java

public static void testLoadOGCServiceMetadata() {
    // String xmlFile =
    // "J:/dev/atoll-v2/atoll-motu/atoll-motu-processor/src/test/resources/xml/TestServiceMetadata.xml";
    String xmlFile = "C:/Documents and Settings/dearith/Mes documents/Atoll/SchemaIso/TestServiceMetadataOK.xml";

    String schemaPath = "schema/iso19139";

    try {//from  w  ww  .  j av  a  2  s  .com
        List<String> errors = validateServiceMetadataFromString(xmlFile, schemaPath);
        if (errors.size() > 0) {
            StringBuffer stringBuffer = new StringBuffer();
            for (String str : errors) {
                stringBuffer.append(str);
                stringBuffer.append("\n");
            }
            throw new MotuException(String.format("ERROR - XML file '%s' is not valid - See errors below:\n%s",
                    xmlFile, stringBuffer.toString()));
        } else {
            System.out.println(String.format("XML file '%s' is valid", xmlFile));
        }

    } catch (MotuException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    InputStream in = null;
    try {
        in = Organizer.getUriAsInputStream(xmlFile);
    } catch (MotuException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    JAXBContext jc = null;
    try {
        // jc = JAXBContext.newInstance("org.isotc211.iso19139.d_2006_05_04.srv");
        // jc = JAXBContext.newInstance("org.isotc211.iso19139.d_2006_05_04.srv");
        jc = JAXBContext
                .newInstance(new Class[] { org.isotc211.iso19139.d_2006_05_04.srv.ObjectFactory.class });
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        Source srcFile = new StreamSource(xmlFile);
        JAXBElement<?> element = (JAXBElement<?>) unmarshaller.unmarshal(srcFile);
        // JAXBElement<?> element = (JAXBElement<?>) unmarshaller.unmarshal(in);
        SVServiceIdentificationType serviceIdentificationType = (SVServiceIdentificationType) element
                .getValue();
        // serviceIdentificationType = (SVServiceIdentificationType) unmarshaller.unmarshal(in);
        System.out.println(serviceIdentificationType.toString());

        List<SVOperationMetadataPropertyType> operationMetadataPropertyTypeList = serviceIdentificationType
                .getContainsOperations();

        for (SVOperationMetadataPropertyType operationMetadataPropertyType : operationMetadataPropertyTypeList) {

            SVOperationMetadataType operationMetadataType = operationMetadataPropertyType
                    .getSVOperationMetadata();
            System.out.println("---------------------------------------------");
            if (operationMetadataType == null) {
                continue;
            }
            System.out.println(operationMetadataType.getOperationName().getCharacterString().getValue());
            System.out.println(operationMetadataType.getInvocationName().getCharacterString().getValue());
            System.out.println(operationMetadataType.getOperationDescription().getCharacterString().getValue());

            CIOnlineResourcePropertyType onlineResourcePropertyType = operationMetadataType.getConnectPoint()
                    .get(0);
            if (onlineResourcePropertyType != null) {
                System.out.println(operationMetadataType.getConnectPoint().get(0).getCIOnlineResource()
                        .getLinkage().getURL());
            }

            List<SVParameterPropertyType> parameterPropertyTypeList = operationMetadataType.getParameters();

            for (SVParameterPropertyType parameterPropertyType : parameterPropertyTypeList) {
                SVParameterType parameterType = parameterPropertyType.getSVParameter();

                if (parameterType.getName().getAName().getCharacterString() != null) {
                    System.out.println(parameterType.getName().getAName().getCharacterString().getValue());
                } else {
                    System.out.println("WARNING - A parameter has no name");

                }
                if (parameterType.getDescription() != null) {
                    if (parameterType.getDescription().getCharacterString() != null) {
                        System.out.println(parameterType.getDescription().getCharacterString().getValue());
                    } else {
                        System.out.println("WARNING - A parameter has no description");

                    }
                } else {
                    System.out.println("WARNING - A parameter has no description");

                }
            }

        }
        FileWriter writer = new FileWriter("c:/tempVFS/test.xml");

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.marshal(element, writer);

        writer.flush();
        writer.close();

        System.out.println("End testLoadOGCServiceMetadata");
    } catch (JAXBException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:com.ephesoft.dcma.util.XMLUtil.java

/**
 * To Output html Stream for ISO Encoding.
 * /*  w  ww  .jav a2  s .c o  m*/
 * @param pathOfHOCRFile String
 * @param outputFilePath String
 * @return FileWriter
 * @throws IOException
 */
public static void htmlOutputStreamForISOEncoding(final String pathOfHOCRFile, final String outputFilePath)
        throws IOException {

    Tidy tidy = new Tidy();
    tidy.setXHTML(true);
    tidy.setDocType(DOC_TYPE_OMIT);
    tidy.setInputEncoding(ISO_ENCODING);
    tidy.setOutputEncoding(ISO_ENCODING);
    tidy.setHideEndTags(false);

    FileInputStream inputStream = null;
    FileWriter outputStream = null;
    try {
        inputStream = new FileInputStream(pathOfHOCRFile);
        outputStream = new FileWriter(outputFilePath);
        tidy.parse(inputStream, outputStream);
    } finally {
        if (null != inputStream) {
            inputStream.close();
        }
        if (null != outputStream) {
            outputStream.flush();
            outputStream.close();
        }
    }
}

From source file:com.comcast.cdn.traffic_control.traffic_router.core.dns.ZoneManager.java

private static void writeZone(final Zone zone) throws IOException {
    synchronized (LOGGER) {
        if (!zoneDirectory.exists() && !zoneDirectory.mkdirs()) {
            LOGGER.error(zoneDirectory.getAbsolutePath() + " directory does not exist and cannot be created!");
        }//  w  ww .j  a v  a  2s . c o  m

        final File zoneFile = new File(getZoneDirectory(), zone.getOrigin().toString());
        final FileWriter w = new FileWriter(zoneFile);
        LOGGER.info("writing: " + zoneFile.getAbsolutePath());
        IOUtils.write(zone.toMasterFile(), w);
        w.flush();
        w.close();
    }
}

From source file:de.andrena.tools.macker.plugin.CommandLineFileTest.java

public void testInvokeEmptyFile() throws Exception {
    FileWriter out = new FileWriter(TEST_FILE);
    out.flush();
    out.close();/*from   w ww  . ja v a2 s.c om*/

    CommandLineFile.main(new String[] { SetArgs.class.getName(), TEST_FILE.toString() });
    assertNotNull(SetArgs.getLastArgs());
    assertEquals(0, SetArgs.getLastArgs().length);
}

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 {/*from  w  w w.j  a  va  2s  .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:freightKt.KTFreight_v3.java

/**
 * Prft ob alle Services auch in den geplanten Touren vorkommen, d.h., ob sie auhc tatschslcih geplant wurden.
 * Falls nicht: log.Error und Ausgabe einer Datei: "#UnassignedServices.txt" mit den Service-Ids.
 * @param carriers//www  .  java2 s  . co  m
 */

//TODO: Ausgabe der Anassigned Services in Run-Verzeichnis und dafrin der bersicht nur eine Nennung der Anzahl unassignedServices je Run 
//TODO: multiassigned analog.
private static void checkServiceAssignment(Carriers carriers) {
    for (Carrier c : carriers.getCarriers().values()) {
        ArrayList<CarrierService> assignedServices = new ArrayList<CarrierService>();
        ArrayList<CarrierService> multiassignedServices = new ArrayList<CarrierService>();
        ArrayList<CarrierService> unassignedServices = new ArrayList<CarrierService>();

        System.out.println("### Carrier: " + c.getId());
        //Erfasse alle einer Tour zugehrigen (-> stattfindenden) Services 
        for (ScheduledTour tour : c.getSelectedPlan().getScheduledTours()) {
            for (TourElement te : tour.getTour().getTourElements()) {
                if (te instanceof ServiceActivity) {
                    CarrierService assigService = ((ServiceActivity) te).getService();
                    if (!assignedServices.contains(assigService)) {
                        assignedServices.add(assigService);
                        System.out.println("Assigned Service: " + assignedServices.toString());
                    } else {
                        multiassignedServices.add(assigService);
                        log.error("Service wurde von dem Carrier " + c.getId().toString()
                                + " bereits angefahren: " + assigService.getId().toString());
                    }
                }
            }
        }

        //Nun prfe, ob alle definierten Service zugeordnet wurden
        for (CarrierService service : c.getServices()) {
            System.out.println("Service to Check: " + service.toString());
            if (!assignedServices.contains(service)) {
                System.out.println("Service not assigned: " + service.toString());
                unassignedServices.add(service);
                log.error("Service wird von Carrier " + c.getId().toString() + " NICHT bedient: "
                        + service.getId().toString());
            } else {
                System.out.println("Service was assigned: " + service.toString());
            }
        }

        //Schreibe die mehrfach eingeplanten Services in Datei
        if (!multiassignedServices.isEmpty()) {
            try {
                FileWriter writer = new FileWriter(new File(TEMP_DIR + "#MultiAssignedServices.txt"), true);
                writer.write("#### Multi-assigned Services of Carrier: " + c.getId().toString()
                        + System.getProperty("line.separator"));
                for (CarrierService s : multiassignedServices) {
                    writer.write(s.getId().toString() + System.getProperty("line.separator"));
                }
                writer.flush();
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //Schreibe die nicht eingeplanten Services in Datei
        if (!unassignedServices.isEmpty()) {
            try {
                FileWriter writer = new FileWriter(new File(TEMP_DIR + "#UnassignedServices.txt"), true);
                writer.write("#### Unassigned Services of Carrier: " + c.getId().toString()
                        + System.getProperty("line.separator"));
                for (CarrierService s : unassignedServices) {
                    writer.write(s.getId().toString() + System.getProperty("line.separator"));
                }
                writer.flush();
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    } //for(carriers)

}