All pastes #170620 Raw Edit

Untitled

public java v1 · immutable
·published 2006-09-14 18:12 UTC
rendered paste body
//i have to write a program that asks the user to enter the name of a file, //and then asks the user to enter a character. the program should count and display //the number of times that the specified character appears in the file.import java.util.Scanner; //Needed for Scanner Classimport java.io.*; //Needed for file classespublic class FileReader{private static String getFileContents(String fileName) {File file = new File(fileName);FileInputStream fio = null;byte [] data = null;String buffer = null;try {if (file.exists()) {fio = new FileInputStream(file);data = new byte[fio.available()];fio.read(data);buffer = new String(data);} elseSystem.out.println("File (" + fileName + ") does not exist");}catch (Exception io) {System.out.println(io.getMessage());}finally {if (fio != null) {try {fio.close();}catch (Exception fioerror) {fioerror.getMessage();}}}if (buffer==null)buffer = "";return buffer;}private static int countCharacters(String buffer, String testChr) {int count = 0;int startIndex = 0, sindex;while ((sindex = buffer.indexOf(testChr, startIndex)) >= 0) {startIndex = sindex+1;count++;}return count;}private static int countCharactersInFile(String fileName, String testChr) {String buffer = getFileContents(fileName);return countCharacters(buffer, testChr);}public static void main(String[] args) throws IOException{String filename; //File nameString Char; // Character a-z or A-Z//Create a Scanner object for keyboard inputScanner keyboard = new Scanner(System.in);//Get the Character from a-z or A-ZSystem.out.print("Please enter a file to scan ?");filename = keyboard.nextLine();System.out.print("Please enter a character a-z or A-Z ?");Char = keyboard.nextLine();System.out.println("Count of character(" + Char + ") in file (" + filename + ") is " + countCharactersInFile(filename, Char));}}