如何读取文本文件、搜索逗号、将逗号视为新行并使用 Java 将其导出到新文件?
How can I read a text file, search for commas, treat commas as new lines, and export it to a new file using Java?
我有一个 .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,
......
有什么建议吗?
所以整个文件只有一行?如果是这样,您只需执行以下操作:
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);
}
}
我有一个 .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,
......
有什么建议吗?
所以整个文件只有一行?如果是这样,您只需执行以下操作:
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);
}
}