2

我正在开始编写我的程序(这是为了一堂课),我遇到了麻烦,只是把它写下来。这是我希望实现的目标列表。

  1. 这是一个给定 .txt 文件的方法(使用 java.io.File)
  2. 它需要读取文件并拆分单词,允许重复。(我打算使用 String.split 和 util.regex.Pattern 来计算空格和标点符号)
  3. 我的目标是将单词放在一维数组中,然后找到数组的长度。

我遇到的问题是解析 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。至少这对我有用。谢谢大家的意见!

4

3 回答 3

3
BufferedReader input = new BufferedReader(new FileReader(filename));

input.readLine();

这是我用来从文件中读取的内容。请注意,您必须处理 IOException

于 2013-08-26T16:03:33.423 回答
1

这是JSE 6.0 Scanner API的链接

以下是完成项目所需的信息:

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<String> 和 ArrayList 或 LinkedList。如果您不需要随机访问单词,LinkedList 是您的最佳选择。

于 2013-08-26T16:20:59.477 回答
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/

于 2013-08-26T16:33:23.127 回答