如何读取文本文件、搜索逗号、将逗号视为新行并使用Java将其导出到新文件?
我有一个.txt文件,其中有10亿个条目,用逗号分隔。我希望能够读取file.txt文件,允许脚本读取逗号,将逗号前的项目复制到新文件中,并在每个逗号后开始新行 当前文本文件格式的示例:如何读取文本文件、搜索逗号、将逗号视为新行并使用Java将其导出到新文件?,java,text,bufferedreader,filereader,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,
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);
}
}
你只是想。。。要在您的文件中添加10亿
\n
?为什么?它将大大增加文件的大小,而不会使用。另外,如果这是你想做的,这是一件非常基本的事情,你可以用它作为灵感。在没有新行的情况下读取文件有点棘手。一个好问题应该包括您尝试了什么,以及您遇到了什么问题。我使用了ReadFile、splits、delims,但没有成功。我的代码看起来更复杂。谢谢你,DUUUDE123。你的代码成功了。