-2

I have a .txt file with 1 billion items separated by commas. I want to be able to read the file.txt file, allow my script to read the commas, copy the item before the comma into a new file, and start a new line after every comma.

Example of the current text file format:

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

Desired output:

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

any suggestion?

azurefrog
  • 10,785
  • 7
  • 42
  • 56
joshua
  • 57
  • 1
  • 1
  • 7
  • 1
    You just want... to add 1 billion `\n` in your file ? Why ? It will dramatically increase the size of the file for no use. Plus, if this is what you want to do, this is a very basic thing – Dici Apr 28 '15 at 21:43
  • 1
    You can use this as inspiration. http://stackoverflow.com/questions/22135261/getting-byte-offset-of-line-in-a-text-file Reading a file without new lines is a little tricky. – RisingSun Apr 28 '15 at 21:43
  • A good question would include what you tried, and where you are stuck. – Erick Robertson Apr 28 '15 at 23:30

1 Answers1

0

So the entire file is just one line? If that is the case, all you would have to do is the following:

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);
    }
}
DUUUDE123
  • 166
  • 1
  • 10
  • I was using ReadFile, splits, delims, and I was not successful. My code looked more complex. Thank you DUUUDE123. Your code worked. – joshua Apr 29 '15 at 17:08