List of usage examples for java.io LineNumberReader close
public void close() throws IOException
From source file:org.intermine.install.properties.MinePropertiesLoader.java
/** * Write out the mine's user configuration properties file. This bases its format * on the file as it exists in the Intermine user home directory, writing lines verbatim * except for those where it has been supplied a property value. If no such file exists, * a standard template is used as the basis. * //from w ww . j av a 2 s .c o m * @param mineName The name of the mine. * @param props The mine's user configuration properties. * * @throws IOException if there is a problem performing the write. */ public static void saveProperties(String mineName, Properties props) throws IOException { File minePropertiesFile = getMinePropertiesFile(mineName); File mineBackupFile = null; Reader sourceReader; if (minePropertiesFile.exists()) { mineBackupFile = new File(minePropertiesFile.getParentFile(), minePropertiesFile.getName() + "~"); if (mineBackupFile.exists()) { mineBackupFile.delete(); } boolean ok = minePropertiesFile.renameTo(mineBackupFile); if (!ok) { throw new IOException("Failed to create backup file for " + minePropertiesFile.getAbsolutePath()); } sourceReader = new FileReader(mineBackupFile); } else { if (intermineUserHome.exists()) { if (!intermineUserHome.isDirectory()) { throw new IOException(intermineUserHome.getAbsolutePath() + " is not a directory."); } } else { boolean ok = intermineUserHome.mkdir(); if (!ok) { throw new IOException("Failed to create directory " + intermineUserHome.getAbsolutePath()); } } InputStream in = MinePropertiesLoader.class.getResourceAsStream(PROPERTIES_TEMPLATE); if (in == null) { throw new FileNotFoundException(PROPERTIES_TEMPLATE); } sourceReader = new InputStreamReader(in); } LineNumberReader reader = new LineNumberReader(sourceReader); try { PrintWriter writer = new PrintWriter(new FileWriter(minePropertiesFile)); try { String line; while ((line = reader.readLine()) != null) { Matcher m = PROPERTY_PATTERN.matcher(line); if (m.matches()) { String key = m.group(1); if (props.containsKey(key)) { writer.print(key); writer.print('='); writer.println(props.get(key)); } else { writer.println(line); } } else { writer.println(line); } } } finally { writer.close(); } } finally { reader.close(); } }
From source file:com.sds.acube.ndisc.xnapi.XNApiUtils.java
private static void readVersionFromFile() { XNApi_PublishingVersion = "<unknown>"; XNApi_PublishingDate = "<unknown>"; InputStreamReader isr = null; LineNumberReader lnr = null; try {/*from w w w .j a va 2s . co m*/ isr = new InputStreamReader( XNApiUtils.class.getResourceAsStream("/com/sds/acube/ndisc/xnapi/version.txt")); if (isr != null) { lnr = new LineNumberReader(isr); String line = null; do { line = lnr.readLine(); if (line != null) { if (line.startsWith("Publishing-Version=")) { XNApi_PublishingVersion = line.substring("Publishing-Version=".length(), line.length()) .trim(); } else if (line.startsWith("Publishing-Date=")) { XNApi_PublishingDate = line.substring("Publishing-Date=".length(), line.length()) .trim(); } } } while (line != null); lnr.close(); } } catch (IOException ioe) { XNApi_PublishingVersion = "<unknown>"; XNApi_PublishingDate = "<unknown>"; } finally { try { if (lnr != null) { lnr.close(); } if (isr != null) { isr.close(); } } catch (IOException ioe) { } } }
From source file:Main.java
@SuppressLint("HardwareIds") static String getPhoneMacAddress(Context context) { String mac = ""; InputStreamReader inputStreamReader = null; LineNumberReader lineNumberReader = null; try {/*from w w w .j a va 2 s. c o m*/ @SuppressLint("WifiManagerPotentialLeak") WifiManager manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); WifiInfo info = manager.getConnectionInfo(); mac = info.getMacAddress(); if (TextUtils.isEmpty(mac)) { Process process = Runtime.getRuntime().exec("cat /sys/class/net/wlan0/address"); inputStreamReader = new InputStreamReader(process.getInputStream()); lineNumberReader = new LineNumberReader(inputStreamReader); String line = lineNumberReader.readLine(); if (line != null) { mac = line.trim(); } } } catch (IOException ex) { ex.printStackTrace(); } finally { if (inputStreamReader != null) { try { inputStreamReader.close(); } catch (Exception e) { e.printStackTrace(); } } if (lineNumberReader != null) { try { lineNumberReader.close(); } catch (Exception e) { e.printStackTrace(); } } } if (TextUtils.isEmpty(mac)) { mac = "na"; } return mac; }
From source file:com.codecrate.shard.transfer.pcgen.PcgenObjectImporter.java
private int getNumberOfFileLines(File file) { int lines = 0; try {// w w w . j a v a 2 s . c o m long lastByte = file.length(); LineNumberReader lineRead = new LineNumberReader(new FileReader(file)); lineRead.skip(lastByte); lines = lineRead.getLineNumber() - 1; lineRead.close(); } catch (IOException e) { LOG.warn("Error counting the number of lines in file: " + file, e); } return lines; }
From source file:org.opensha.commons.util.FileUtils.java
/** * Loads in each line to a text file into an ArrayList ( i.e. a vector ). Each * element in the ArrayList represents one line from the file. * * @param fileName File to load in * @return ArrayList each element one line from the file * @throws FileNotFoundException If the filename doesn't exist * @throws IOException Unable to read from the file *//*w ww .j av a 2s. com*/ public static ArrayList<String> loadFile(String fileName, boolean skipBlankLines) throws FileNotFoundException, IOException { // Debugging String S = C + ": loadFile(): "; if (D) System.out.println(S + "Starting"); if (D) System.out.println(S + fileName); // Allocate variables ArrayList<String> list = new ArrayList<String>(); File f = new File(fileName); // Read in data if it exists if (f.exists()) { if (D) System.out.println(S + "Found " + fileName + " and loading."); boolean ok = true; int counter = 0; String str; FileReader in = new FileReader(fileName); LineNumberReader lin = new LineNumberReader(in); while (ok) { try { str = lin.readLine(); if (str != null) { //omit the blank line if (skipBlankLines && str.trim().equals("")) continue; list.add(str); if (D) { System.out.println(S + counter + ": " + str); counter++; } } else ok = false; } catch (IOException e) { ok = false; } } lin.close(); in.close(); if (D) System.out.println(S + "Read " + counter + " lines from " + fileName + '.'); } else if (D) System.out.println(S + fileName + " does not exist."); // Done if (D) System.out.println(S + "Ending"); return list; }
From source file:eu.eexcess.diversityasurement.wikipedia.RDFCategoryExtractor.java
private long getTotalNumberOfLines(File file) throws FileNotFoundException, IOException { long lines = 0; LineNumberReader lineNumberReader = new LineNumberReader(new FileReader(file)); lineNumberReader.skip(Long.MAX_VALUE); lines = lineNumberReader.getLineNumber(); lineNumberReader.close(); return lines; }
From source file:org.openmrs.module.initializer.AddressHierarchyMessagesLoadingTest.java
@Test @Verifies(value = "should load i18n messages specific to the address hierarchy configuration", method = "refreshCache()") public void refreshCache_shouldLoadAddressHierarchyMessages() throws IOException { // Replay// w w w .j av a2 s . c om inizSrc.refreshCache(); AddressConfigurationLoader.loadAddressConfiguration(); AddressHierarchyService ahs = Context.getService(AddressHierarchyService.class); ahs.initI18nCache(); InitializerService iniz = Context.getService(InitializerService.class); File csvFile = (new ConfigDirUtil(iniz.getConfigDirPath(), iniz.getChecksumsDirPath(), iniz.getRejectionsDirPath(), InitializerConstants.DOMAIN_ADDR)) .getConfigFile("addresshierarchy.csv"); LineNumberReader lnr = new LineNumberReader(new FileReader(csvFile)); lnr.skip(Long.MAX_VALUE); int csvLineCount = lnr.getLineNumber() + 1; lnr.close(); Assert.assertTrue(csvLineCount < ahs.getAddressHierarchyEntryCount()); // there should be more entries than the // number of lines in CSV import // Working in km_KH Context.getUserContext().setLocale(new Locale("km", "KH")); PersonAddress address = new PersonAddress(); address.setStateProvince(""); address.setCountyDistrict(""); address.setAddress1("??"); // Looking for possible villages based on an address provided in km_KH AddressHierarchyLevel villageLevel = ahs.getAddressHierarchyLevelByAddressField(AddressField.CITY_VILLAGE); List<AddressHierarchyEntry> villageEntries = ahs.getPossibleAddressHierarchyEntries(address, villageLevel); Assert.assertFalse(CollectionUtils.isEmpty(villageEntries)); // Verifying that possible villages are provided as i18n message codes final Set<String> expectedVillageNames = new HashSet<String>(); // filled by looking at the test CSV expectedVillageNames.add("addresshierarchy.tangTonle"); expectedVillageNames.add("addresshierarchy.rumloung"); expectedVillageNames.add("addresshierarchy.thlokChheuTeal"); expectedVillageNames.add("addresshierarchy.trachChrum"); expectedVillageNames.add("addresshierarchy.paelHael"); expectedVillageNames.add("addresshierarchy.krangPhka"); expectedVillageNames.add("addresshierarchy.runloungPrakhleah"); expectedVillageNames.add("addresshierarchy.preyKanteach"); expectedVillageNames.add("addresshierarchy.snaoTiPir"); expectedVillageNames.add("addresshierarchy.roleangSangkae"); for (AddressHierarchyEntry entry : villageEntries) { Assert.assertTrue(expectedVillageNames.contains(entry.getName())); } // Pinpointing a specific village address.setCityVillage(""); // Looking for possible villages villageEntries = ahs.getPossibleAddressHierarchyEntries(address, villageLevel); // We should find our one village Assert.assertEquals(1, villageEntries.size()); String messageKey = villageEntries.get(0).getName(); Assert.assertEquals(messageKey, "addresshierarchy.paelHael"); Assert.assertEquals(Context.getMessageSourceService().getMessage(messageKey), ""); }
From source file:edu.stanford.muse.index.NER.java
public static void readLocationsFreebase() throws IOException { InputStream is = new GZIPInputStream(NER.class.getClassLoader().getResourceAsStream("locations.gz")); LineNumberReader lnr = new LineNumberReader(new InputStreamReader(is, "UTF-8")); while (true) { String line = lnr.readLine(); if (line == null) break; StringTokenizer st = new StringTokenizer(line, "\t"); if (st.countTokens() == 3) { String locationName = st.nextToken(); String canonicalName = locationName.toLowerCase(); String lat = st.nextToken(); String longi = st.nextToken(); locations.put(canonicalName, new LocationInfo(locationName, lat, longi)); }//from w ww. j a v a2 s .co m } lnr.close(); }
From source file:eu.fbk.utils.analysis.stemmer.AbstractStemmer.java
/** * Stems a list of terms read from the specified reader. * * @param r the reader//w w w . j av a 2 s. c om */ public void process(Reader r) throws IOException { long begin = 0, end = 0, time = 0; int count = 0; LineNumberReader lnr = new LineNumberReader(r); String line = null; String s = null; while ((line = lnr.readLine()) != null) { begin = System.nanoTime(); s = stem(line); end = System.nanoTime(); time += end - begin; count++; } // end while lnr.close(); logger.info(count + " total " + df.format(time) + " ns"); logger.info("avg " + df.format((double) time / count) + " ns"); }
From source file:de.langmi.spring.batch.examples.complex.file.split.GetLineCountTasklet.java
/** * Short variant to get the line count of the file, there can be problems with files where * the last line has no content./*ww w . j av a 2 s . co m*/ * * @param file * @param chunkContext * @return the line count * @throws IOException * @throws FileNotFoundException */ private int getLineCount(File file) throws IOException, FileNotFoundException { LineNumberReader lnr = null; try { lnr = new LineNumberReader(new FileReader(file)); String line = null; int count = 0; while ((line = lnr.readLine()) != null) { count = lnr.getLineNumber(); } return count; } finally { if (lnr != null) { lnr.close(); } } }