Click to See Complete Forum and Search --> : Needing some help with reading text files...
ddmeightball
Mar 4th, 2005, 12:03 PM
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.
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.
NoteMe
Mar 4th, 2005, 12:44 PM
Simple example:
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);
}
}
Dillinger4
Mar 4th, 2005, 12:58 PM
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.
Dillinger4
Mar 4th, 2005, 01:59 PM
Here's my take on it. Good refresher for me. ;). Didn't count the words though.
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);
}
}
}
Dillinger4
Mar 4th, 2005, 02:38 PM
This should take care of the number of words.
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);
}
}
}
vbforums.com
Copyright Internet.com Inc., All Rights Reserved.