【问题标题】:How can I read a text file, search for commas, treat commas as new lines, and export it to a new file using Java?如何读取文本文件、搜索逗号、将逗号视为换行符并使用 Java 将其导出到新文件?
【发布时间】:2023-04-11 05:29:01
【问题描述】:

我有一个 .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, 
......

有什么建议吗?

【问题讨论】:

  • 您只是想...在您的文件中添加 10 亿 \n 吗?为什么 ?它将大大增加文件的大小而无用。另外,如果这是你想做的,这是一个非常基本的事情
  • 您可以以此为灵感。 stackoverflow.com/questions/22135261/… 读取没有新行的文件有点棘手。
  • 一个很好的问题应该包括你尝试了什么,以及你被困在哪里。

标签: java text bufferedreader filereader


【解决方案1】:

所以整个文件只有一行?如果是这种情况,您只需执行以下操作:

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

【讨论】:

  • 我使用的是ReadFile、splits、delims,但没有成功。我的代码看起来更复杂。谢谢DUUUDE123。您的代码有效。
猜你喜欢
  • 2017-09-05
  • 1970-01-01
  • 2021-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-05
  • 1970-01-01
相关资源
最近更新 更多