this is my code which simply read a file. i just want to add method to it that can count the characters in the text file. please anyone, who can tell me about this code. and about that counter characters method.
regards.
Hasnat Rasool
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class FileRead
{
static int count=0;
public static void main(String[] args)
{
File file = new File("a.txt");
try {
FileInputStream fis = new FileInputStream(file);
char current;
while (fis.available() > 0)
{
current = (char) fis.read();
System.out.print(current);
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
3 Replies - 128 Views - Last Post: 30 December 2012 - 12:56 PM
#1
need simple mathod to count the characters in java from txt file.
Posted 30 December 2012 - 01:52 AM
Replies To: need simple mathod to count the characters in java from txt file.
#2
Re: need simple mathod to count the characters in java from txt file.
Posted 30 December 2012 - 03:16 AM
Hi. The question of course has been asked before many times. You should always use the site search function. I write this not to be mean in any way, but because you cold likely get your answer immediately, instead of having to wait for someone here to reply.
/>
This post has been edited by farrell2k: 30 December 2012 - 03:16 AM
#3
Re: need simple mathod to count the characters in java from txt file.
Posted 30 December 2012 - 12:39 PM
I haven't tested this code; but I think this should achieve your goal:
//do all your imports
private static int numChar(File file){
BufferedReader reader;
int nChars = 0;
String line = "";
try{
reader = new BufferedReader(new FileReader(file));
while(true){
if(line == null)
break;
line = removeDelimeter(line, ' ');
nChars += line.length();
}
reader.close();
}catch(IOException ioe){
}
}
private static String removeDelimeter(String str, char delim){ /*you can use an array of characters if you have more delimeters*/
String temp = "";
for(int i=0; i<str.length(); i++){
if(str.charAt(i) != delim)
temp += delim;
}
return temp;
}
public static void main(String ... args){
File myFile = new File(myFile.txt);
int numberOfCharacters = numChar(myFile);
//do whatever you want with "numberOfCharacters"
}
#4
Re: need simple mathod to count the characters in java from txt file.
Posted 30 December 2012 - 12:56 PM
If, by 'character', you mean letter, then all you need is Character.isLetter©. Otherwise, just count every int read
Page 1 of 1
|
|

New Topic/Question
Reply



MultiQuote




|