【问题标题】:Adding empty lines between sentences in text file在文本文件中的句子之间添加空行
【发布时间】:2015-04-19 15:58:44
【问题描述】:

所以我在一个文本文件中有以下句子:

Something I don't know
Something else as well
And this here
And that

我想让它看起来像这样

Something I don't know

Something else as well

And this here

And that

我知道将内容复制到字符数组中的代码,但我不知道如何在数组之间添加额外的 '\n' 字符。

编辑:添加代码。

import java.io.*;
class File_Tester
{
    public static void main(String[] args)
    {
    int S=0;
    char [] src = new char[300];
    FileReader fr;
    try{
    fr = new FileReader("src.txt");
    fr.read(src);
    fr.close();
    }catch (IOException io) 
    {
     System.out.println(io.toString());
     return;
    }
    for (int i=0;i<src.length;i++)
    {
    if (src[i]==' ') 
    {
     src[i]='@';
     S++;
    }
    else if (src[i]=='\n')
    }
    try{
    File file = new File("dest.txt");
    file.createNewFile();
    FileWriter dest = new FileWriter(file);
    dest.write(src,0,src.length);
    dest.close();
    }catch (IOException io) 
    {
     System.out.println(io.toString());
     return;
    }

   }
}

【问题讨论】:

  • 每行一个句子吗?您不需要 Java 来执行此操作,这可以在命令行中完成。
  • 为什么还要将所有内容复制到char[]?为什么不直接使用Strings/StringBuilders?
  • 如何发布您的代码,而不是让我们猜测它的外观?
  • 添加了代码。我想知道我是否可以使用 for 循环而不是 stringbuilder 来做到这一点(这是一个练习,我不知道我是否可以使用它)
  • 首先阅读docs.oracle.com/javase/tutorial/essential/io/charstreams.html,它展示了如何正确将每个字符从一个文件复制到另一个文件。然后调整它以在需要时插入额外的行分隔符。你的方法完全不正确。

标签: java arrays char newline


【解决方案1】:

您没有说明您使用的是哪个 Java 版本,因此假定为 Java 8:

final Path src = Paths.get("src.txt");
final Path dst = Paths.get("dst.txt");

// Does UTF-8 by default
try (
    final Stream<String> lines = Files.lines(src);
    final BufferedWriter writer = Files.newBufferedWriter(dst);
) {
    lines.forEach(line -> {
        writer.write(line);
        writer.newLine();
        writer.newLine();
    });
}

请注意,这会在文件末尾插入另一个换行符。

【讨论】:

  • 我使用 Java 5,并尝试使其尽可能简单
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多