This is not a difficult task, but I do not get it validated using that regex solution.
My test file content is: less lengthy shortened abbreviation forget why I do not get this going captain kirk
The output: lengthy,shortened,abbreviation,captain
Oh, I attach the requirements in english
The main method's first parameter is file1 and the second is file2.
file1 contains words separated by spaces.
Write to file2 a comma-separated list of words longer than 6 characters.
file2 should not end with a comma.
Close the streams.
Example output to file2:
lengthy,shortened,abbreviation
Requirements:
- The program must NOT read data from the console.
- The program must read the first file's contents (use the FileReader constructor with a String parameter).
- The file input stream (FileReader) must be closed.
- The program should write to the second file all the words from the first file longer than 6 characters, separated by commas (use FileWriter).
- The file output stream (FileWriter) must be closed.
The recommendation from my mentor to requirement 4 is, that I should make sure to write all words that are longer than 6 characters into file 2 (separated by commas).
From what I see I'm doing just this.
In line 29 I'm first replacing all words with more that 6 chars with "" :: replaceAll("\\b\\w{0,6}\\b", "")
So far I tried to substituted \w (word characters) with \S (all non whitespace characters) with no success. Both possibilities lead to the desired result but not to validation.
That replacement may leave some additional spaces, don't know why. Therefore I use trim() to remove them at the beginning and the end
Finally I use again the replaceAll() method to replace all spaces between words with commas :: replaceAll("\\s+", ",") and \s+ cause of the additional remains of the first replaceAll operation
As said, the result looks good to me...
Thanks for helping ;)
Thomas
package de.codegym.task.task19.task1925;
/*
Long words
*/
import java.io.*;
public class Solution {
public static void main(String[] args) throws IOException {
String file1 = args[0];
String file2 = args[1];
BufferedReader reader = new BufferedReader(new FileReader(file1));
FileWriter writer = new FileWriter(file2);
while (reader.ready())
writer.write(longWordList(reader.readLine()));
reader.close();
writer.close();
}
public static String longWordList(String s) {
if (s == null || s.equals(""))
return "";
//1. delete all words <= 6 letters, 2. trim whitespace, 3. replace whitspace between words with commas
return s.replaceAll("\\b\\w{0,6}\\b", "").trim().replaceAll("\\s+", ",");
}
}