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.
This is very simple in Java 8:
First you get your files at
Path
objects.Then you open a
PrintWriter
to your destinationPath
.Now you do some Java 8 stream processing with lambdas:
Files.lines(txt)
streams the lines from the filemap((line) -> line.split("\\|"))
splits each line to aString[]
on|
map((line) -> Stream.of(line).collect(Collectors.joining(",")))
joins the individualString[]
again using,
forEach(pw::println)
writes the new lines to the destination file.Using
import static
:As Java 8 was released only yesterday here is a Java 7 solution:
Again, with
import static
: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?.Yes it is very much possible. Replace | by , and write it to a csv
Output
Yes it is possible. To accomplish your task read about
Input-
andOutputStreams
.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.
try this may help
sample.txt:-
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