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

问题描述 投票:0回答:2

我想在文件中的每个单词之后添加一个空格E.G这最好变成这是一个测试

我能够使用.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.");
   }

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

java file whitespace
2个回答
2
投票

需要单独读取和写入,因为无法在打开的文件上插入,只需按照您的方式添加即可。

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();
}

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


0
投票

以下是一些可以帮助您找到解决问题的方法:

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

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

您可以通过调用在Scanner中使用自定义分隔符 scanner.useDelimiter(",") //e.g. use a comma

当您使用BufferedReader时,您需要通过qazxsw poi拆分读取行,这样您就可以将自定义分隔符指定为参数。

© www.soinside.com 2019 - 2024. All rights reserved.