如何读取文本文件,搜索逗号,将逗号视为新行,并使用Java将其导出到新文件?

时间:2015-04-28 21:39:41

标签: java text bufferedreader filereader

我有一个.txt文件,其中10亿个项目以逗号分隔。我希望能够读取file.txt文件,允许我的脚本读取逗号,将逗号之前的项目复制到新文件中,并在每个逗号后开始一个新行。

当前文本文件格式的示例:

one, twenty one, five, one hundred, seven, ten, iwoi-eiwo, ei123_32323 ... 

期望的输出:

one,
twenty one,
five,
one hundred, 
seven,
ten,
iwoi-eiwo,
ei123_32323, 
......

任何建议?

1 个答案:

答案 0 :(得分:0)

所以整个文件只有一行?如果是这种情况,您只需要做以下事情:

import java.util.Scanner;
import java.io.*;

public class convertToNewline
{
    public static void main(String[] args) throws IOException
    {
        File file = new File("text.txt");
        File file2 = new File("textNoCommas.txt");
        PrintWriter writer = new PrintWriter(file2);
        Scanner reader = new Scanner(file);

        String allText = reader.nextLine();

        allText = allText.replace(", ",   ",");      // replace all commas and spaces with only commas (take out spaces after the commas)
        allText = allText.replace(",",    ",\n");      // replace all commas with a comma and a newline character

        writer.print(allText);
        writer.close();

        System.out.println("Finished printing text.");
        System.out.println("Here was the text:");
        System.out.println(allText);

        System.exit(0);
    }
}