Java Code Examples for java.io.LineNumberReader#skip()

The following examples show how to use java.io.LineNumberReader#skip() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestBigFileRead.java    From basic-tools with MIT License 6 votes vote down vote up
public static long getLineNumber(File file) {
    if (file.exists()) {
        try {
            FileReader fileReader = new FileReader(file);
            LineNumberReader lineNumberReader = new LineNumberReader(fileReader);
            lineNumberReader.skip(Long.MAX_VALUE);
            long lines = lineNumberReader.getLineNumber() + 1;
            fileReader.close();
            lineNumberReader.close();
            return lines;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return 0;
}
 
Example 2
Source File: OldLineNumberReaderTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
public void test_markI() throws IOException {
    lnr = new LineNumberReader(new StringReader(text));
    String line;
    lnr.skip(80);
    lnr.mark(100);
    line = lnr.readLine();
    lnr.reset();
    assertTrue("Test 1: Failed to return to marked position.",
            line.equals(lnr.readLine()));

    lnr.close();
    try {
        lnr.mark(42);
        fail("Test 2: IOException expected.");
    } catch (IOException e) {
        // Expected.
    }

    // The spec does not say the mark has to be invalidated
}
 
Example 3
Source File: BufferedDataSet.java    From NeurophFramework with Apache License 2.0 5 votes vote down vote up
/**
 * Counts and returns number of lines in a file
 * @return number of lines in a file
 * @throws FileNotFoundException
 */
private long countFileLines() throws FileNotFoundException {
    LineNumberReader lnr = new LineNumberReader(new FileReader(file));
    try {
      //  lnr.skip(Long.MAX_VALUE);
       while(lnr.skip(Long.MAX_VALUE) > 0) {};
    } catch (IOException ex) {
        Logger.getLogger(BufferedDataSet.class.getName()).log(Level.SEVERE, null, ex);
    }
    return lnr.getLineNumber() + 1;
}
 
Example 4
Source File: BatchHelper.java    From janusgraph-utils with Apache License 2.0 5 votes vote down vote up
public static long countLines(String filePath) throws Exception {
    LineNumberReader lnr = new LineNumberReader(new FileReader(new File(filePath)));
    try {
        lnr.skip(Long.MAX_VALUE);
        return lnr.getLineNumber() + 1;
    } finally {
        lnr.close();
    }
}
 
Example 5
Source File: LogFileReader.java    From tlaplus with MIT License 5 votes vote down vote up
public long getLineNumbers() throws IOException {
final LineNumberReader reader = new LineNumberReader(new FileReader(logFile));
reader.skip(Long.MAX_VALUE);
final int numberOfLines = reader.getLineNumber();
reader.close();
return numberOfLines;
}
 
Example 6
Source File: SyncthingRunnable.java    From syncthing-android with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Only keep last {@link #LOG_FILE_MAX_LINES} lines in log file, to avoid bloat.
 */
private void trimLogFile() {
    if (!mLogFile.exists())
        return;

    try {
        LineNumberReader lnr = new LineNumberReader(new FileReader(mLogFile));
        lnr.skip(Long.MAX_VALUE);

        int lineCount = lnr.getLineNumber();
        lnr.close();

        File tempFile = new File(mContext.getExternalFilesDir(null), "syncthing.log.tmp");

        BufferedReader reader = new BufferedReader(new FileReader(mLogFile));
        BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));

        String currentLine;
        int startFrom = lineCount - LOG_FILE_MAX_LINES;
        for (int i = 0; (currentLine = reader.readLine()) != null; i++) {
            if (i > startFrom) {
                writer.write(currentLine + "\n");
            }
        }
        writer.close();
        reader.close();
        tempFile.renameTo(mLogFile);
    } catch (IOException e) {
        Log.w(TAG, "Failed to trim log file", e);
    }
}
 
Example 7
Source File: AddressHierarchyMessagesLoadingTest.java    From openmrs-module-initializer with MIT License 4 votes vote down vote up
@Test
@Verifies(value = "should load i18n messages specific to the address hierarchy configuration", method = "refreshCache()")
public void refreshCache_shouldLoadAddressHierarchyMessages() throws IOException {
	
	// Replay
	inizSrc.getCachedMessages();
	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), "ប៉ែលហែល");
}
 
Example 8
Source File: BlastTabularParser.java    From biojava with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public List<Result> createObjects(double maxEScore) throws IOException, ParseException {
	List<Result> results = new ArrayList<Result>();

	log.info("Query for hits");
	LineNumberReader  lnr = new LineNumberReader(new FileReader(targetFile));
	lnr.skip(Long.MAX_VALUE);
	fileLinesCount = lnr.getLineNumber();
	log.info(fileLinesCount + " hits approximately in all results");
	lnr.close();

	FileInputStream fileInputStream = new FileInputStream(targetFile);
	Scanner scanner = new Scanner(fileInputStream);

	String line = fetchData(scanner);
	int lineNumber=0;
	while (lineNumber < fileLinesCount){
		try {
			BlastResultBuilder resultBuilder = new BlastResultBuilder();
			resultBuilder
					.setQueryID(queryId)
					.setDbFile(databaseFile)
					.setProgram(programName)
					.setQueryDef(queryName)
					.setReference(blastReference);

			List<Hit> hits = new ArrayList<Hit>();

			String currentQueryId = queryId;
			while (currentQueryId.equals(queryId) && lineNumber < fileLinesCount){
				BlastHitBuilder hitBuilder = new BlastHitBuilder();

				List<Hsp> hsps = new ArrayList<Hsp>();

				String currentSubjectId=subjectId;
				while (currentSubjectId.equals(subjectId) && lineNumber < fileLinesCount){
					if (new Double(evalue) > maxEScore) {
						line = fetchData(scanner);
						lineNumber++;
						continue;
					}
					BlastHspBuilder hspBuilder = new BlastHspBuilder();
					hspBuilder
						.setHspAlignLen(new Integer(alnLength))
						.setHspGaps(new Integer(gapOpenCount))
						.setHspQueryFrom(new Integer(queryStart))
						.setHspQueryTo(new Integer(queryEnd))
						.setHspHitFrom(new Integer(subjectStart))
						.setHspHitTo(new Integer(subjectEnd))
						.setHspEvalue(new Double(evalue))
						.setHspBitScore(new Double(bitScore))
						.setPercentageIdentity(new Double(percIdentity)/100)
						.setMismatchCount(new Integer(mismatchCount));
					hsps.add(hspBuilder.createBlastHsp());
					if (scanner.hasNext()) line = fetchData(scanner);
					lineNumber++;
				}
				hits.add(hitBuilder.setHsps(hsps).createBlastHit());
			}
			results.add(resultBuilder.setHits(hits).createBlastResult());
		} catch (NumberFormatException e) {
			throw new ParseException("Invalid numeric value met at line "+ lineNumber+" in:\n"+line,0);
		}
	}
	return results;
}
 
Example 9
Source File: CountLinesTextFile.java    From levelup-java-examples with Apache License 2.0 3 votes vote down vote up
@Test
public void count_lines_text_java() throws IOException {

	LineNumberReader lineReader = new LineNumberReader(new FileReader(Paths
			.get(fileLocation).toFile()));
	lineReader.skip(Long.MAX_VALUE);

	long totalNumberOfLines = lineReader.getLineNumber() + 1;

	lineReader.close();

	assertEquals(10, totalNumberOfLines);
}