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

时间:2019-04-16 13:12:51

标签: java file whitespace

我想在文件中的每个单词之后添加一个空格 E.G 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.");
   }

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

2 个答案:

答案 0 :(得分:2)

一个人需要单独读写,因为不能在打开的文件中“ <插入>插入”,只能像您一样追加。

Traceback (most recent call last):
  File "/home/pi/env/bin/googlesamples-assistant-hotword", line 10, in <module>
    sys.exit(main())
  File "/home/pi/env/lib/python3.5/site-packages/googlesamples/assistant/library/hotword.py", line 154, in main
    process_event(event)
  File "/home/pi/env/lib/python3.5/site-packages/googlesamples/assistant/library/hotword.py", line 59, in process_event
    print(event)
UnicodeEncodeError: 'latin-1' codec can't encode character '\U0001f4a8' in position 48: ordinal not in range(256)

在这里,我将这些行读为单行的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>加上空格。

但是,将“ thisisatest”分解为需要英语知识的单词。

\\s+

由于这看起来像是家庭作业,或者至少应该进行一些有趣的工作,其余的工作取决于您。

答案 1 :(得分:0)

以下问题可能会帮助您找到解决问题的方法:

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

因此,无论您如何解决问题,都将需要有一个分隔符,用于分隔您所说的单词。确切地说,我将其称为Token

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

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