我正在编写我的程序(这是一个类),我遇到了麻烦,只是把它写下来。这是我希望见到的目标清单。
我遇到的问题是解析txt文件。我在课堂上被告知Scanner可以,但是我在R(ing)TFM时找不到它。我想我在API中要求一些方向,这有助于我了解如何使用Scanner读取文件。一旦我能够将每个单词放入数组中,我就应该清楚了。
编辑:由于每个人的帮助和意见,我想出了我需要做什么。如果将来有人遇到这个问题,我的最终片段最终会看起来像这样。Scanner in = new Scanner(file).useDelimiter(" ");
ArrayList<String> prepwords=new ArrayList<String>();
while(in.hasNext())
prepwords.add(in.next());
return prepwords; //returns an ArrayList without spaces but still has punctuation
我不得不抛出IOExceptions,因为java讨厌不确定文件是否存在,所以如果你遇到“FileNotFoundException”,你需要导入并抛出IOException。至少这对我有用。谢谢大家的意见!
答案 0 :(得分:3)
BufferedReader input = new BufferedReader(new FileReader(filename));
input.readLine();
这是我用来从文件中读取的内容。请注意,您必须处理IOException
答案 1 :(得分:1)
以下是完成项目所需的信息:
1. Use the Scanner(File) constructor.
2. Use a loop that is, essentially this:
a. Scanner blam = new Scanner(theInputFile);
b. Map<String, Integer> wordMap = new HashMap<String, Integer>();
c. Set<String> wordSet = new HashSet<String>();
d. while (blam.hasNextLine)
e. String nextLine = blam.nextLine();
f. Split nextLine into words (head about the read String.split() method).
g. If you need a count of words: for each word on the line, check if the word is in the map, if it is, increment the count. If not, add it to the map. This uses the wordMap (you dont need wordSet for this solution).
h. If you just need to track the words, add each word on the line to the set. This uses the wordSet (you dont need wordMap for this solution).
3. that is all.
如果你不需要地图或集合,那么使用List&lt; String&gt;以及ArrayList或LinkedList。如果您不需要随机访问单词,可以使用LinkedList。
答案 2 :(得分:0)
简单的事情:
//variables you need
File file = new File("someTextFile.txt");//put your file here
Scanner scanFile = new Scanner(new FileReader(file));//create scanner
ArrayList<String> words = new ArrayList<String>();//just a place to put the words
String theWord;//temporary variable for words
//loop through file
//this looks at the .txt file for every word (moreover, looks for white spaces)
while (scanFile.hasNext())//check if there is another word
{
theWord = scanFile.next();//get next word
words.add(theWord);//add word to list
//if you dont want to add the word to the list
//you can easily do your split logic here
}
//print the list of words
System.out.println("Total amount of words is: " + words.size);
for(int i = 0; i<words.size(); i++)
{
System.out.println("Word at " + i + ": " + words.get(i));
}
来源:
http://www.dreamincode.net/forums/topic/229265-reading-in-words-from-text-file-using-scanner/