Needing some help with reading text files...
I just want to post this here, cause once i get an up and running version of my code, i will post it here to get some help with it.
Quote:
Write a program that reads a text file and reports the number of characters, lines and words contained in the file. Use a GUI.
File I/O is set up to read the text file
Uses FileReader class
Uses BufferedReader stream
Uses readline() to get a line of data, loop to read all the data.
Counts lines
Counts characters
Count words using a StringTokenizer
Program compiles and runs correctly. Follows coding standards.
Re: Needing some help with reading text files...
Simple example:
Code:
public void ReadFromFile(String fileName) {
try {
FileInputStream indatafile = new FileInputStream(fileName);
DataInputStream readObject = new DataInputStream(indatafile);
//Read all you want or what ever.
readObject.close();
}
catch (IOException someError) {
System.out.print("Error reading: " + someError);
}
}
Re: Needing some help with reading text files...
For the line count you could use a LineNumberReader(Reader in) and use the method getLineNumber() which should return the last line read which would be the sum of all the lines that were read by the stream.
Re: Needing some help with reading text files...
Here's my take on it. Good refresher for me. ;). Didn't count the words though.
Code:
import java.io.*;
public class X{
public static void main(String[] args){
try{
BufferedReader buff = new BufferedReader(
new FileReader("C://" + File.separator + "test.txt"));
int numlines = 0;
String s = "";
String finalstring = "";
while((s = buff.readLine ())!= null){
finalstring += s;
numlines = ++numlines;
}
buff.close();
System.out.println("There are " + finalstring.length() + " characters in the file");
System.out.println("There are " + numlines + " lines in the file");
}catch(IOException io){
System.err.println(io);
}
}
}
Re: Needing some help with reading text files...
This should take care of the number of words.
Code:
import java.io.*;
import java.util.*;
public class X{
public static void main(String[] args){
try{
BufferedReader buff = new BufferedReader(
new FileReader("C://" + File.separator + "test.txt"));
int numlines = 0;
int numwords = 0;
String s = "";
String finalstring = "";
while((s = buff.readLine ())!= null){
finalstring += s + " ";
numlines = ++numlines;
}
StringTokenizer st = new StringTokenizer(finalstring);
while(st.hasMoreTokens()){
numwords = ++numwords;
st.nextToken();
}
buff.close();
System.out.println("There are " + (finalstring.length() - numwords) + " characters in the file");
System.out.println("There are " + numwords + " words in the file");
System.out.println("There are " + numlines + " lines in the file");
}catch(IOException io){
System.err.println(io);
}
}
}