(java) - 将输入文件中的每个单词存储在字符串数组中

时间:2015-02-21 08:18:11

标签: java arrays

在编写方法来完成此任务时遇到问题,请先了解方法的基本概要,但只需要一些指针/帮助完成此操作。

  public static String [] readFileAndReturnWords(String filename){
     //create array
     //read one word at a time from file and store in array
     //return the array
  }

这是我到目前为止所做的:

public static String readFileAndReturnWords(String filename){   
      String[] temp = new String[];

      //connects file
      File file = new File(filename);
      Scanner inputFile = null;

     try{

          inputFile = new Scanner(file);

         }
          //When arg is mistyped
      catch(FileNotFoundException Exception1) {
          System.out.println("File not found!");
          System.exit(0);      
     }


     //Loops through a file
    if (inputFile != null) {

    try { //I draw a blank here

我理解一些.next和.hasNext调用是有序的,我只是不确定如何在问题的上下文中使用这些特定的方法。

2 个答案:

答案 0 :(得分:3)

分裂成单个单词实际上比最初看起来有点棘手 - 你分开了什么?

如果你拆分空格,那么fullstops,逗号和其他标点符号将最终附加到一个单词,所以

  快,懒狗。

将分为:

  1. 快,
  2. 懒惰
  3. 狗。
  4. 哪些可能是您想要的,也可能不是。如果你拆分非单词字符然后你最终分裂撇号,连字符等,所以:

    • 不能,不会 - >
      1. 可以
      2. 赢得
    • 没有人怀疑超空间
      1. 没有
      2. 一个
      3. 嫌疑人
      4. 空间

    因此,这些解决方案各有其问题。我建议使用word boundary正则表达式匹配器。它有点复杂,但仍有问题 - 尝试不同的方法,看看是什么产生了你需要的输出。

    我建议的解决方案使用Java 8:

    public static String[] readFileAndReturnWords(String filename) throws IOException {
        final Path path = Paths.get(filename);
        final Pattern pattern = Pattern.compile("\\b");
    
        try (final Stream<String> lines = Files.lines(path)) {
            return lines.flatMap(pattern::splitAsStream).toArray(String[]::new);
        }
    }
    

    首先,您将String转换为Path,即文件位置的Java NIO表示。然后创建Pattern,这决定了如何分解单词。

    如何简单地使用Files.lines流式传输文件中的所有行,然后Pattern.splitAsStream将每行转换为单词。我们使用flatMap,因为我们需要“展平”流,即每行都是Stream<String>,我们已经有Stream<String>,因此我们最终得到Stream<Stream<String>>flatMap旨在获取Stream<Stream<T>>并返回Stream<T>

答案 1 :(得分:2)

将其存储在ArrayList中,因为您不知道文件中存储了多少字。

public class Test
{
  static ArrayList<String> words;
  public static void main(String[] args) throws FileNotFoundException
  {
    Scanner s = new Scanner(new File("Blah.txt"));
    words = new ArrayList<String>();
    while(s.hasNext ())
    {
      String token = s.next ();
      if(isAWord(token))
      {
        if(token.contains ("."))
        {
         token =  token.replace (".","");
        }
        if(token.contains (","))
        {
          token = token.replace (",", "");
        }
        //and remove other characters like braces and parenthesis 
        //since the scanner gets tokens like
        // here we are, < "are," would be a token
        //
        words.add(token);
      }

    }

  }

  private static boolean isAWord(String token)
  {
    //check if the token is a word
  }
}

它应该有用。

如果你真的想使用数组,你可以通过

将ArrayList转换为一个简单的数组
String[] wordArray = words.toArray();