在文本文件中的句子之间添加空行

时间:2015-04-19 15:58:45

标签: java arrays char newline

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

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

   }
}

1 个答案:

答案 0 :(得分:0)

您不会说出您使用的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();
    });
}

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