3

Is it possible to create a Java program which recognizes the text in a .txt file and write it in a .csv file? If yes,how would you start with such a problem?

My .txt file is Text1 |Text 2 so I could somehow get the char "|" and split it into two cells.

Sandeep Chatterjee
  • 3,220
  • 9
  • 31
  • 47
user3333587
  • 55
  • 1
  • 1
  • 4
  • 1
    Yes, look at [String.split](http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#split%28java.lang.String%29). – Alexander_Winter Mar 20 '14 at 07:56
  • 4
    @BoristheSpider Yes Java is an overkill for such a task, but he asked for it. Maybe he want to use it as a function of a bigger program. – Alexander_Winter Mar 20 '14 at 07:59
  • @user3333587 this is a problem that can probably be implemented in just about any programming language out there. –  Mar 20 '14 at 08:09

6 Answers6

10

This is very simple in Java 8:

public static void main(String[] args) throws Exception {
    final Path path = Paths.get("path", "to", "folder");
    final Path txt = path.resolve("myFile.txt");
    final Path csv = path.resolve("myFile.csv");
    try (
            final Stream<String> lines = Files.lines(txt);
            final PrintWriter pw = new PrintWriter(Files.newBufferedWriter(csv, StandardOpenOption.CREATE_NEW))) {
        lines.map((line) -> line.split("\\|")).
                map((line) -> Stream.of(line).collect(Collectors.joining(","))).
                forEach(pw::println);
    }
}

First you get your files at Path objects.
Then you open a PrintWriter to your destination Path.

Now you do some Java 8 stream processing with lambdas:

  • Files.lines(txt) streams the lines from the file
  • map((line) -> line.split("\\|")) splits each line to a String[] on |
  • map((line) -> Stream.of(line).collect(Collectors.joining(","))) joins the individual String[] again using ,
  • forEach(pw::println) writes the new lines to the destination file.

Using import static:

    try (
            final Stream<String> lines = Files.lines(txt);
            final PrintWriter pw = new PrintWriter(newBufferedWriter(csv, StandardOpenOption.CREATE_NEW))) {
        lines.map((line) -> line.split("\\|")).
                map((line) -> Stream.of(line).collect(joining(","))).
                forEach(pw::println);
    }

As Java 8 was released only yesterday here is a Java 7 solution:

public static void main(String[] args) throws Exception {
    final Path path = Paths.get("path", "to", "folder");
    final Path txt = path.resolve("myFile.txt");
    final Path csv = path.resolve("myFile.csv");
    final Charset utf8 = Charset.forName("UTF-8");
    try (
            final Scanner scanner = new Scanner(Files.newBufferedReader(txt, utf8));
            final PrintWriter pw = new PrintWriter(Files.newBufferedWriter(csv, utf8, StandardOpenOption.CREATE_NEW))) {
        while (scanner.hasNextLine()) {
            pw.println(scanner.nextLine().replace('|', ','));
        }
    }
}

Again, with import static:

    try (
            final Scanner scanner = new Scanner(newBufferedReader(txt, utf8));
            final PrintWriter pw = new PrintWriter(newBufferedWriter(csv, utf8, StandardOpenOption.CREATE_NEW))) {
        while (scanner.hasNextLine()) {
            pw.println(scanner.nextLine().replace('|', ','));
        }
    }
Boris the Spider
  • 59,842
  • 6
  • 106
  • 166
2

Yes it is very much possible. Replace | by , and write it to a csv

public class NewClass {

public static void main(String[] args) throws IOException {

   String data = "one|two|three|four"+"\n"+
           "one|two|three|four";
   //Use a BufferedReader to read from actual Text file
    String csv = data.replace("|", ",");
    System.out.println(csv);

    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("MyCSV.csv")));
    out.println(csv);
    out.close();
}
}

Output

run:
one,two,three,four
one,two,three,four
BUILD SUCCESSFUL (total time: 0 seconds)
  • You may want to escape double quote(") and comma(,). For example, you split each row by |, and for each column we need to escape double quote and comma. – Bae Cheol Shin Jul 14 '16 at 21:34
0

You first need to How do I create a Java string from the contents of a file?.

Then you can take advantage of How to split a string in Java and use | as the delimiter.

As the last step you can use the Joiner to create the final String and store it using How do I save a String to a text file using Java?.

Community
  • 1
  • 1
Wojciech Owczarczyk
  • 5,595
  • 2
  • 33
  • 55
  • Why on earth would you read the whole file into memory?! Streaming line by line would be a much more practical approach. And recommending a third party library when it is unnecessary because a) writing the code yourself is 3 lines and b) Java 8 already has this functionality. – Boris the Spider Mar 20 '14 at 07:58
  • @BoristheSpider if the file happens to be small, I wouldn't consider the memory usage to be a big deal. This is the original poster's first Java program. It's probably just for practice. –  Mar 20 '14 at 08:02
  • @BoristheSpider I generally try to encourage new programmers to use third party libraries so in the future they are not spending to much time on reinventing wheels. Good point about streaming, but as Cupcake noted it kinda depends on the size of the input. – Wojciech Owczarczyk Mar 20 '14 at 08:05
  • While it is admirable to encourage new developers not to reinvent wheels, to do so at the expense of learning the Java API is anathema. Java 8 already has a joining collector: `List.stream().collect(Collectors.joining(delim))`. – Boris the Spider Mar 20 '14 at 08:29
  • Yeah... but Java 8 was officially released yesterday :) But you are absolutely right, that if a given functionality exists in standard JDK we should use it first. – Wojciech Owczarczyk Mar 20 '14 at 08:45
0

Yes it is possible. To accomplish your task read about Input- and OutputStreams.

Start with a simple example. Read a line of text from a file and print it out on the console. Then do it the other way - write a line of text into a file.

The experience you get through these examples will help to accomplish your task.

Markus
  • 1,649
  • 1
  • 22
  • 41
0

try this may help

    public class Test {

    public static void main(String[] args) throws URISyntaxException,
            IOException {

        FileWriter writer = null;
        File file = new File("d:/sample.txt");
        Scanner scan = new Scanner(file);
        File file2 = new File("d:/CSV.csv");
        file.createNewFile();
        writer = new FileWriter(file2);

        while (scan.hasNext()) {
            String csv = scan.nextLine().replace("|", ",");
            System.out.println(csv);
            writer.append(csv);
            writer.append("\n");
            writer.flush();
        }
    }
}

sample.txt:-

  He|looked|for|a|book.

  He|picked|up|the|book.
Shekhar Khairnar
  • 2,643
  • 3
  • 26
  • 44
0

Commons CSV is useful for handling CSV output in your Java code too - in particular it takes care of gotchas such as quoting, etc:

http://commons.apache.org/proper/commons-csv/

Also commons IO is really useful for simplifying reading/writing files too:

https://commons.apache.org/proper/commons-io/description.html

HTH

Geoff Williams
  • 1,320
  • 10
  • 15