📄 filewordreader.java
字号:
package eclipse.workspace.Word.src;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.StreamTokenizer;
/**
* A class to read words from a file, one word at a time.
* Personal note: I do not like the StreamTokenizer class used below as it is unwieldy and inelegant.
* However, it is very expedient in this example.
*
* @author Justin Templemore-Finlayson, ECE
*
*/
public class FileWordReader
{
private StreamTokenizer stream;
private long wordCount;
/**
* Creates an FileWordReader object that reads one word at a time from the specified text file.
* The text file must be located in the current working directory (in eclipse, this is the root
* directory of the project).
* @param fileName
* @throws FileNotFoundException
*/
public FileWordReader (String fileName) throws FileNotFoundException
{
stream = new StreamTokenizer (new FileReader(new File (fileName))); // looks for character file in current dir
wordCount = 0;
}
/**
* Gets the next word from the file.
* If there are no more words, the method returns a null.
* @return The next word.
*/
public String getNextWord()
{
String word = null;
int tokenType;
do {
try
{
tokenType = stream.nextToken ();
if (tokenType == StreamTokenizer.TT_WORD)
{
word = stream.sval;
wordCount++;
}
}
catch (IOException e)
{
word = null;
break;
}
}
while (tokenType != StreamTokenizer.TT_EOF && word == null);
return word;
}
/**
* Returns the number of words counted by this object.
* @return The number of words counted so far
*/
public long getWordCount()
{
return wordCount;
}
/**
* Short program to test my method
* @param args
*/
public static void main(String[] args)
{
FileWordReader fwr;
try
{
fwr = new FileWordReader ("story.txt");
System.out.println ("OK! File found!");
String word = fwr.getNextWord();
while (word != null)
{
System.out.println ("* " + word);
word = fwr.getNextWord();
}
System.out.println ("Finished reading. There were " + fwr.getWordCount() + " words.");
} catch (FileNotFoundException e)
{
System.out.println ("KO! File not found!");
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -