List of usage examples for java.io FileReader close
public void close() throws IOException
From source file:com.jagornet.dhcp.db.DbSchemaManager.java
public static List<String> getSchemaDDL(String schemaFilename) throws IOException { List<String> schema = new ArrayList<String>(); FileReader fr = null; BufferedReader br = null;/* w w w. ja v a 2s . co m*/ try { StringBuilder ddl = new StringBuilder(); if (JagornetDhcpServer.springBootStrategy) { String cpFileName = schemaFilename.substring(schemaFilename.lastIndexOf("/") + 1, schemaFilename.length()); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); InputStream res = classLoader.getResourceAsStream(cpFileName); br = new BufferedReader(new InputStreamReader(res, "UTF-8")); } else { fr = new FileReader(schemaFilename); br = new BufferedReader(fr); } String line = br.readLine(); while (line != null) { if (!line.startsWith("-- ")) { ddl.append(line); } if (ddl.toString().endsWith(";")) { ddl.setLength(ddl.length() - 1); schema.add(ddl.toString()); ddl.setLength(0); } line = br.readLine(); } } finally { if (br != null) { br.close(); } if (fr != null) { fr.close(); } } return schema; }
From source file:buspathcontroller.JSONFileParser.java
public void generateRouteStopsAndPath() { JSONParser parser = new JSONParser(); ArrayList<String> routeList = new ArrayList<String>(); try {/*from ww w . j av a2s . c o m*/ FileReader reader = new FileReader("/Users/Zhaowei/Desktop/BusPath/allRoutes.txt"); BufferedReader br = new BufferedReader(reader); String line; while ((line = br.readLine()) != null) { String routeName = line.split(";")[1]; routeList.add(routeName); } br.close(); reader.close(); Iterator<String> it = routeList.iterator(); while (it.hasNext()) { String routeName = it.next(); PrintWriter writer = new PrintWriter( "/Users/Zhaowei/Desktop/BusPath/routeInfo/stops/" + routeName + ".txt"); Object obj = parser.parse( new FileReader("/Users/Zhaowei/Desktop/BusPath/RawJSON/route/" + routeName + ".json")); JSONObject jsonObject = (JSONObject) obj; JSONObject route = (JSONObject) jsonObject.get("route"); JSONArray directions = (JSONArray) route.get("directions"); for (int i = 0; i < directions.size(); i++) { JSONObject direction = (JSONObject) directions.get(i); writer.println(direction.get("direction")); JSONArray stops = (JSONArray) direction.get("stops"); Iterator iter = stops.iterator(); while (iter.hasNext()) { JSONObject stop = (JSONObject) iter.next(); writer.println(stop.get("stopnumber") + ";" + stop.get("stoptitle") + ";" + stop.get("stoplat") + ";" + stop.get("stoplng")); } } writer.close(); } } catch (Exception e) { System.out.println(e); } }
From source file:com.npower.unicom.sync.SyncResultWriter.java
/** * Writer/*from ww w . j av a2s . c o m*/ * @throws IOException */ public void close() throws IOException { this.bodyWriter.close(); File outputFile = null; // String requestFilename = this.requestFile.getName(); String reponseFilename = requestFilename.substring(0, requestFilename.length() - ".req".length()) + ".res"; if (this.totalRecords == this.successRecords) { // File outputDir = new File(this.responseDir, SUB_DIR_FOR_RIGHT); if (!outputDir.exists()) { log.info("create directory: " + outputDir.getAbsolutePath()); outputDir.mkdirs(); } outputFile = new File(outputDir, reponseFilename); } else if (this.totalRecords == this.errorRecords) { // File outputDir = new File(this.responseDir, SUB_DIR_FOR_BAD); if (!outputDir.exists()) { log.info("create directory: " + outputDir.getAbsolutePath()); outputDir.mkdirs(); } outputFile = new File(outputDir, reponseFilename); } else { // File outputDir = new File(this.responseDir, SUB_DIR_FOR_SEMI_WRONG); outputFile = new File(outputDir, reponseFilename); if (!outputDir.exists()) { log.info("create directory: " + outputDir.getAbsolutePath()); outputDir.mkdirs(); } } log.info("output reponse file: " + outputFile.getAbsolutePath()); // SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss"); RequestHeader header = RequestHeader.parseHeaderInfo(this.requestFile); Writer writer = new FileWriter(outputFile); writer.write(header.getSerialNumber()); writer.write('\t'); writer.write(header.getVersion()); writer.write('\t'); writer.write(format.format(new Date())); writer.write('\t'); writer.write(""); writer.write('\t'); writer.write(this.totalRecords); writer.write('\t'); writer.write(this.successRecords); writer.write('\t'); writer.write('\n'); if (this.totalRecords != this.successRecords && this.totalRecords != this.errorRecords) { // FileReader in = new FileReader(this.bodyFile); char[] buf = new char[512]; int len = in.read(buf); while (len > 0) { writer.write(buf, 0, len); len = in.read(buf); } in.close(); } writer.close(); }
From source file:org.kalypso.model.hydrology.internal.postprocessing.LzsToGml.java
private void readChannelStartCondition(final Channel channel) throws Exception { final int asciiID = m_idManager.getAsciiID(channel); final String fileName = String.format("we%s.lzg", asciiID); //$NON-NLS-1$//$NON-NLS-2$ final File lzgFile = new File(m_lzsimDir, fileName); if (!lzgFile.exists()) // FIXME: shoudn't we throw some exception here? return;/*from w w w . j a v a 2 s . c o m*/ final InitialValues initialValues = (InitialValues) m_lzWorkspace.getRootFeature(); final IFeatureBindingCollection<org.kalypso.model.hydrology.binding.initialValues.Channel> channels = initialValues .getChannels(); final org.kalypso.model.hydrology.binding.initialValues.Channel iniChannel = channels .addNew(org.kalypso.model.hydrology.binding.initialValues.Channel.FEATURE_CHANNEL); iniChannel.setNaChannelID(channel); iniChannel.setName(Integer.toString(asciiID)); //$NON-NLS-1$ //$NON-NLS-2$ FileReader fileReader = null; try { fileReader = new FileReader(lzgFile); final double qgs = readLzgFile(fileReader); fileReader.close(); if (!Double.isNaN(qgs)) iniChannel.setQgs(qgs); } finally { IOUtils.closeQuietly(fileReader); } }
From source file:org.kalypso.model.hydrology.internal.postprocessing.LzsToGml.java
private void readCatchmentStartCondition(final Catchment catchment) throws Exception { final InitialValues initialValues = (InitialValues) m_lzWorkspace.getRootFeature(); final IFeatureBindingCollection<org.kalypso.model.hydrology.binding.initialValues.Catchment> catchments = initialValues .getCatchments();//from w w w .j a v a 2 s.co m final org.kalypso.model.hydrology.binding.initialValues.Catchment iniCatchment = catchments .addNew(org.kalypso.model.hydrology.binding.initialValues.Catchment.FEATURE_CATCHMENT); iniCatchment.setNaCatchmentID(catchment); final int asciiID = m_idManager.getAsciiID(catchment); iniCatchment.setName(Integer.toString(asciiID)); //$NON-NLS-1$ //$NON-NLS-2$ final String fileName = String.format("we%s.lzs", asciiID); //$NON-NLS-1$ final File lzsFile = new File(m_lzsimDir, fileName); FileReader fileReader = null; try { fileReader = new FileReader(lzsFile); readLzsFile(fileReader, catchment, iniCatchment); fileReader.close(); } catch (final NumberFormatException e) { m_logger.severe(String.format(Messages.getString("LzsToGml.0"), e.getLocalizedMessage())); //$NON-NLS-1$ } catch (final IOException e) { m_logger.warning( Messages.getString("org.kalypso.convert.namodel.manager.LzsimManager.27", catchment.getName())); //$NON-NLS-1$ } finally { IOUtils.closeQuietly(fileReader); } }
From source file:it.txt.ens.client.subscriber.impl.osgi.test.BasicENSSubscriberTest.java
@Test public void testUseOfBasicENSSubscriber() throws Exception { Thread.currentThread().setContextClassLoader(BasicENSSubscriberTest.class.getClassLoader()); assertNotNull("The bundle context is null", context); File propertiesFile = new File(PROPERTIES_RELATIVE_PATH); FileReader reader = null; Properties properties = new Properties(); try {/*w w w .j a v a 2 s .c o m*/ reader = new FileReader(propertiesFile); properties.load(reader); reader.close(); } catch (FileNotFoundException e) { // if (LOGGER.isLoggable(Level.SEVERE)) // LOGGER.log(Level.SEVERE, MessageFormat.format(LOG_MESSAGES.getString("propertyFile.notFound"), // propertiesFile.getAbsolutePath()), e); System.out.println("Properties file not found. File: " + propertiesFile.getAbsolutePath()); e.printStackTrace(); } finally { if (reader != null) try { reader.close(); } catch (IOException e) { } } //add implementation ID properties.setProperty(FilterAttributes.SUBSCRIBER_IMPLEMENTATION_KEY, BasicENSSubscriber.IMPLEMENTATION_ID); //add ownership id properties.setProperty(FilterAttributes.SUBSCRIBER_OWNER_KEY, String.valueOf(context.getBundle().getBundleId())); //retrieve the configuration admin service ServiceReference<ConfigurationAdmin> configAdminSR = context.getServiceReference(ConfigurationAdmin.class); ConfigurationAdmin configAdmin = context.getService(configAdminSR); Configuration config = configAdmin .createFactoryConfiguration(RegisteredServices.SUBSCRIBER_MANAGED_SERVICE_FACTORY_PID, null); config.update(MapConverter.convert(properties)); context.ungetService(configAdminSR); // Collection<ServiceReference<ENSSubscriber>> references = null; EqualsFilter implementationFilter = new EqualsFilter(FilterAttributes.SUBSCRIBER_IMPLEMENTATION_KEY, BasicENSSubscriber.IMPLEMENTATION_ID); EqualsFilter ownershipFilter = new EqualsFilter(FilterAttributes.SUBSCRIBER_OWNER_KEY, String.valueOf(context.getBundle().getBundleId())); AndFilter and = new AndFilter().and(implementationFilter).and(ownershipFilter); String serviceRegistryFilter = and.toString(); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Filtering OSGi service registry with query " + serviceRegistryFilter + ". Class: " + ENSSubscriber.class.getName()); } int i = 0; //FIXME add a timeout otherwise we could wait forever! (aspitt semb!) do { i++; references = context.getServiceReferences(ENSSubscriber.class, serviceRegistryFilter); } while (references.isEmpty()); System.out.println("Cycle counter " + i); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Count of services found: " + references.size()); } assertEquals("Bad count of " + ENSSubscriber.class.getName() + " found.", 1, references.size()); ServiceReference<ENSSubscriber> serviceRef = references.iterator().next(); // ServiceReference<ENSSubscriber> serviceRef = context.getServiceReference(ENSSubscriber.class); assertNotNull("The service reference is null", serviceRef); // System.out.println("SERVICE REFERENCE PROPERTIES"); // for (String key : serviceRef.getPropertyKeys()) // System.out.println(key + ": " + serviceRef.getProperty(key)); ENSSubscriber subscriber = context.getService(serviceRef); assertNotNull("The subscriber is null", subscriber); subscriber.connect(); subscriber.registerEventListener(new ENSEventListener() { @Override public void onEvent(ENSEvent event) { System.out.println(event.getPattern()); } }); subscriber.subscribe(); Thread.sleep(50000); subscriber.unsubscribe(); subscriber.disconnect(); context.ungetService(serviceRef); }
From source file:marytts.tools.voiceimport.PraatPitchmarker.java
/** * Provide the progress of computation, in percent, or -1 if * that feature is not implemented.//w w w. j a v a 2 s . com * @return -1 if not implemented, or an integer between 0 and 100. */ public int getProgress() { // hack to get progress from Praat through file I/O: File percentFile = new File(db.getProp(db.TEMPDIR) + "percent"); if (percentFile.exists()) { percent = -1; try { FileReader percentReader = new FileReader(percentFile); String percentString = IOUtils.toString(percentReader); percent = Integer.parseInt(percentString); percentReader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return percent; }
From source file:gov.nih.nci.caintegrator.domain.analysis.GisticAllLesionsFileParser.java
/** * * @param inputFile input file/*from w w w . j a v a2 s . c o m*/ * @throws IOException IO exception * @throws DataRetrievalException data retrieval exception * @return GISTIC data mapping */ public Map<String, Map<GisticGenomicRegionReporter, Float>> parse(File inputFile) throws IOException, DataRetrievalException { FileReader fileReader = new FileReader(inputFile); CSVReader csvReader = new CSVReader(fileReader, '\t'); loadHeaders(csvReader); String[] fields; regionReporterIndex = 0; while ((fields = csvReader.readNext()) != null) { processDataLine(fields); } csvReader.close(); fileReader.close(); FileUtils.deleteQuietly(inputFile); return gisticData; }
From source file:it.geosolutions.unredd.StatsTests.java
@Test public void outputCSVTest() throws IOException { StatisticConfiguration config = new StatisticConfiguration(); Output outputObj = new Output(); outputObj.setFile(TestData.temp(this, "stats.txt").getAbsolutePath()); outputObj.setFormat(Output.FORMAT_CSV); config.setOutput(outputObj);//from w ww .j av a2s. com OutputStatsTest ost = new OutputStatsTest(config); ost.outputStats(results); File f = new File(ost.getOutputFile()); FileReader fr = new FileReader(f); BufferedReader br = new BufferedReader(fr); StringBuilder sb = new StringBuilder(); for (String line; (line = br.readLine()) != null;) { sb.append(line); } fr.close(); br.close(); assertEquals("0,1,", sb.toString()); }
From source file:it.geosolutions.unredd.StatsTests.java
@Test public void outputJSON_ARRAYTest() throws IOException { StatisticConfiguration config = new StatisticConfiguration(); Output outputObj = new Output(); outputObj.setFile(TestData.temp(this, "stats.txt").getAbsolutePath()); outputObj.setFormat(Output.FORMAT_JSON_ARRAY); config.setOutput(outputObj);//from w ww. ja v a 2 s . co m OutputStatsTest ost = new OutputStatsTest(config); ost.outputStats(results); File f = new File(ost.getOutputFile()); FileReader fr = new FileReader(f); BufferedReader br = new BufferedReader(fr); StringBuilder sb = new StringBuilder(); for (String line; (line = br.readLine()) != null;) { sb.append(line); } fr.close(); br.close(); assertEquals("[[0],[1]]", sb.toString()); }