Java tutorial
//package com.java2s; /* * Copyright (C) 2010-12 Ciaran Gultnieks, ciaran@ciarang.com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import java.io.Closeable; import java.io.File; import java.io.FileReader; import java.io.IOException; public class Main { public static int countSubstringOccurrence(File file, String substring) throws IOException { int count = 0; FileReader input = null; try { int currentSubstringIndex = 0; char[] buffer = new char[4096]; input = new FileReader(file); int numRead = input.read(buffer); while (numRead != -1) { for (char c : buffer) { if (c == substring.charAt(currentSubstringIndex)) { currentSubstringIndex++; if (currentSubstringIndex == substring.length()) { count++; currentSubstringIndex = 0; } } else { currentSubstringIndex = 0; } } numRead = input.read(buffer); } } finally { closeQuietly(input); } return count; } public static void closeQuietly(Closeable closeable) { if (closeable == null) { return; } try { closeable.close(); } catch (IOException ioe) { // ignore } } }