在文件中的每个单词后添加空格 (Java)



我想在文件中的每个单词后面添加一个空格例如,thisisatest 变成了这是一个测试

我能够让它使用 .write 在文件末尾添加一个空格

这是我用来添加空格的代码

try {
    String filename = "test.txt";
    FileWriter fw = new FileWriter(filename,true);
    fw.write(" ");
    fw.close();
} catch(IOException ioe)
  {
      System.err.println("IOException: " + ioe.getMessage());
  }

这是我用来查找单词的代码

 try {
     File file = new File(WORD_FILE);
     Scanner scanner = new Scanner(file);
     while (scanner.hasNextLine()) {
         String line = scanner.nextLine();
         for(String word : line.split("\s")) {
            if (!word.isEmpty())
                System.out.println(word);
          }
      }
      scanner.close();
   } catch (FileNotFoundException e) {
        System.out.println("File not found.");
   }

它在文件末尾添加了一个空格,但我希望它做的是在每个单词后添加一个空格

一个人需要单独读取和写入,因为不能插入打开的文件,只需像你一样附加。

String filename = "test.txt";
Charset charset = Charset.defaultCharset(); // StandardCharsets.UTF_8
Path path = Paths.get(filename);
List<String> lines = Files.lines(path, charset)
    .map(line -> line.replaceAll("\s+", "$0 "))
    .collect(Collectors.toList());
Files.write(path, lines, charset);

在这里,我将这些行解读为单行Stream<String>。我用相同的空格加上一个额外的空格替换空格\s+

但是,要将"thisisatest"拆分为单词,您需要英语知识。

    .map(line -> replaceWords(line))
List<String> allWords = Arrays.asList(
    "are", "a",
    "island", "is",
    "tests", "test",
    "thistle", "this", "th" /*5th*/
);
String replaceWords(String line) {
    StringBuilder sb = new StringBuilder();
    ... loop through letter sequences (multiple words)
    ... and split them by sorted dictionary.
    return sb.toString();
}

由于这看起来像家庭作业,或者至少应该保留一些有趣的努力,其余的取决于您。

这里有一些可以帮助您找到解决问题的方法:

您遇到的问题是扫描仪读取所谓的Token,并且为了分离令牌,扫描仪使用Delimiter 。默认分隔符是 whitespace

因此,无论您如何解决问题,您都需要有一个分隔符来分隔您所谓的单词。准确地说,我称之为Token.

Scanner您可以通过调用
scanner.useDelimiter(",") //e.g. use a comma

当您使用 BufferedReader 时,您需要按 String.split() 拆分读取行,这样您就可以指定自定义分隔符作为参数。

最新更新