Search code examples
javafilestring-parsing

Java File Parsing - Go word by word


I have a file content as Follows:

Sample.txt: Hi my name is john and I am an engineer. How are you

The output I want is an arrayList of string like [Hi,my,name,is,john,and,I,am,an,engineer,.,How,are,you]

The standard java function parses it as line and I would get an array containing the lines. I am confused as to which approach I should use to get the following output.

Any help is appretiated.


Solution

  • If you are getting the strings as whole lines, but just want the words, you could use .split(" ") on the words, as this would return an array containing individual words with no spaces. If you want to do this within the file reading, you could use something like the following...

    public ArrayList<String> readWords(File file) throws IOException {
      ArrayList<String> words = new ArrayList<String>();
      String cLine = "";
      BufferedReader reader = new BufferedReader(new FileReader(file));
      while ((cLine = reader.readLine()) != null) {
        for (String word : cLine.split(" ")) {words.add(word);}
      }
      reader.close();
      return words;
    }
    

    which would return an ArrayList<String> containing all of the individual words in the file.

    Hope this helps.