Parse .txt to .csv - java

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:
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('|', ','));
}
}

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 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 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.

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.

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

Related

Read UTF-8 properties file and save as UTF-8 txt file

I am currently trying to analyze all of my properties files and need my properties files in the form of a .txt file for one part. The problem is that german "Umlaute" like Ä,Ü,Ö etc. are not taken over correctly and therefore my program does not work. (If I convert the files manually into a txt there are no problems, but the whole thing should run dynamically)
Here is my code I am currently using:
private static void createTxt(String filePath, String savePath) throws IOException {
final File file = new File(filePath);
final BufferedReader bReader = new BufferedReader(new FileReader(file.getPath()));
final List<String> stringList= new ArrayList<>();
String line = bReader.readLine();
while (line != null) {
stringList.add(line);
line = bReader.readLine();
}
final Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(savePath), "UTF-8"));
try {
for (final String s : stringList) {
out.write(s + "\n");
}
}
finally {
out.close();
}
}
The encoding of the txt is also UTF-8 - I think the problem is due to the bufferedReader or caching into the ArrayList
Thank you for your time and help,
LG Pascal
When reading and writing files you should always set a charset. FileReader has a constructor that takes a Charset.
new FileReader(file, StandardCharsets.UTF_8)
If you just want to read all lines from a file just use Files.readAllLines(path, StandardCharsets.UTF_8);
To write you can use Files.write(path, listOfStrings, StandardCharsets.UTF_8);
And if you only want to copy the files, just use Files.copy(source, target);

Java input and output stream from file path

How does one use a specified file path rather than a file from the resource folder as an input or output stream? This is the class I have and I would like to read from a specific file path instead of placing the txt file in the resources folder in IntelliJ. Same for an output stream. Any help rendered would be appreciated thanks.
Input Stream
import java.io.*;
import java.util.*;
public class Example02 {
public static void main(String[] args) throws FileNotFoundException {
// STEP 1: obtain an input stream to the data
// obtain a reference to resource compiled into the project
InputStream is = Example02.class.getResourceAsStream("/file.txt");
// convert to useful form
Scanner in = new Scanner(is);
// STEP 2: do something with the data stream
// read contents
while (in.hasNext()) {
String line = in.nextLine();
System.out.println(line);
}
// STEP 3: be polite, close the stream when done!
// close file
in.close();
}
}
Output stream
import java.io.*;
public class Example03
{
public static void main(String []args) throws FileNotFoundException
{
// create/attach to file to write too
// using the relative filename will cause it to create the file in
// the PROJECT root
File outFile = new File("info.txt");
// convert to a more useful writer
PrintWriter out = new PrintWriter(outFile);
//write data to file
for(int i=1; i<=10; i++)
out.println("" + i + " x 5 = " + i*5);
//close file - required!
out.close();
}
}
Preferred way for getting InputStream is java.nio.file.Files.newInputStream(Path)
try(final InputStream is = Files.newInputStream(Paths.get("/path/to/file")) {
//Do something with is
}
Same for OutputStream Files.newOutputStream()
try(final OutputStream os = Files.newOutputStream(Paths.get("/path/to/file")) {
//Do something with os
}
Generally, here is official tutorial from Oracle to working with IO.
First you have to define the path you want to read the file from, absolute path like so:
String absolutePath = "C:/your-dir/yourfile.txt"
InputStream is = new FileInputStream(absolutePath);
It's similar for writing the file as well:
String absolutePath = "C:/your-dir/yourfile.txt"
PrintWriter out = new PrintWriter(new FileOutputStream(absolutePath));
You can use a file object as:
File input = new File("C:\\[Path to file]\\file.txt");

Write to files using Java

I am trying to use lists for my first time, I have a txt file that I am searching in it about string then I must write the result of searching in new file.
Check the image attached
My task is to retrieve the two checked lines of the input file to the output files.
And this is my code:
import java.io.*;
import java.util.Scanner;
public class TestingReport1 {
public static void main(String[] args) throws Exception {
File test = new File("E:\\test2.txt");
File Result = new File("E:\\Result.txt");
Scanner scanner = new Scanner(test);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if(line.contains("Visit Count")|| line.contains("Title")) {
System.out.println(line);
}
}
}
}
What should I do?!
Edit: How can I write the result of this code into text file?
Edit2:
Now using the following code:
public static void main(String[] args) throws Exception {
// TODO code application logic here
File test = new File("E:\\test2.txt");
FileOutputStream Result = new FileOutputStream("E:\\Result.txt");
Scanner scanner = new Scanner(test);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if(line.contains("Visit Count")|| line.contains("Title")) {
System.out.println(line);
Files.write(Paths.get("E:\\Result.txt"), line.getBytes(), StandardOpenOption.APPEND);
}
}
}
I got the result back as Visit Count:1 , and I want to get this number back as integer, Is it possible?
Have a look at Files, especially readAllLines as well as write. Filter the input between those two method calls, that's it:
// Read.
List<String> input = Files.readAllLines(Paths.get("E:\\test2.txt"));
// Filter.
String output = input.stream()
.filter(line -> line.matches("^(Title.*|Visit Count.*)"))
.collect(Collectors.joining("\n"));
// Write.
Files.write(Paths.get("E:\\Result.txt"), output.getBytes());

File write/read function like in PHP

So I'm learning new things day by day in Java, and I hope one day I should have same knowledge in Java as in PHP.
I'm trying to make a class that is similar to fopen, fwrite, fclose in PHP like:
<?php
$fp = fopen('data.txt', 'w');
fwrite($fp, '1');
fwrite($fp, '23');
fclose($fp);
// the content of 'data.txt' is now 123 and not 23!
?>
I also need the method of writing
o - for delete and write/overwrite
a - for append at end
and a read function that returns the the content line by line, so I can put it into an array , like file_get_contents(file);
This is what I have so far ...
import java.io.*;
import java.util.Scanner;
/**
Read and write a file using an explicit encoding.
Removing the encoding from this code will simply cause the
system's default encoding to be used instead.
**/
public final class readwrite_txt
{
/** Requires two arguments - the file name, and the encoding to use. **/
public static void main(String[] args) throws IOException
{
String fileName = "text.txt";
String encoding = "UTF-8";
readwrite_txt test = new readwrite_txt(fileName,encoding);
test.write("argument.txt","some text","UTF-8","o");
}
/** Constructor. **/
readwrite_txt(String fileName, String encoding)
{
String fEncoding = "text.txt";
String fFileName = "UTF-8";
}
/** Write fixed content to the given file. **/
public void write(String fileName,String input,String encoding,String writeMethod) throws IOException
{
// Method overwrite
if(writeMethod == "o")
{
log("Writing to file named " + fileName + ". Encoding: " + encoding);
Writer out = new OutputStreamWriter(new FileOutputStream(fileName), encoding);
try
{
out.write(input);
}
finally
{
out.close();
}
}
}
/** Read the contents of the given file. **/
public void read(String fileName,String output,String encoding,String outputMethod) throws IOException
{
log("Reading from file.");
StringBuilder text = new StringBuilder();
String NL = System.getProperty("line.separator");
Scanner scanner = new Scanner(new FileInputStream(fileName), encoding);
try
{
while (scanner.hasNextLine())
{
text.append(scanner.nextLine() + NL);
}
}
finally
{
scanner.close();
}
log("Text read in: " + text);
}
// Why write System.out... when you can make a function like log("message"); simple!
private void log(String aMessage)
{
System.out.println(aMessage);
}
}
also, I don't understand why I must have
readwrite_txt test = new readwrite_txt(fileName,encoding);
instead of
readwrite_txt test = new readwrite_txt();
I just want to have an simple function similar to that in PHP.
EDITED
So my function must be
$fp = fopen('data.txt', 'w'); ==> readwrite_txt test = new readwrite_txt(filename,encoding,writeMethod);
fwrite($fp, '23'); ==> test.write("the text");
fclose($fp); ==> ???
to read a file in java you can
FileInputStream fstream = new FileInputStream("file.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
while ((strLine = br.readLine()) != null) //Start of reading file
{
//what you want to do with every line is here
}
but for readwrite_txt test = new readwrite_txt(); problem ..
you must have another constructor inside the class that doesn't take any parameters
Have a look at the following file handling tutorials (Google is littered with them):
http://www.javapractices.com/topic/TopicAction.do?Id=42
http://www.coderanch.com/t/403914/java/java/do-read-entire-file-all
Pay attention to the following classes:
FileInputStream
FileOutpuStream
Scanner
There's all sorts of examples out there for you to learn from.
You can use the BufferedReader, here is an example and BufferedWriter, here is an example of write and here is an example for appending. For reading line-by-line you can use the readLine method of BufferedReader. You don't need those parameters in your constructor, because you don't use them, but you don't even need a class to implement these features because there are already standard classes for this purpose.
I hope this helps.

Re-Writing to java txt files

i was wondering if there was a way to add to text files already created. because when i do this on an already created file:
public Formatter f = new Formatter("filename.txt");
it re-writes the current filename.txt with a blank one.
thanks, Quinn
Yes, use the constructor with an OutputStream argument instead of a File argument. That way you can open an OutputStream in append mode and do your formatting on that. Link
Try using the constructor for Formatter which takes an Appendable as an argument.
There are several classes which implement the Appendable interface. The most convenient, in your case, should be FileWriter.
This FileWrite constructor will let you open a file (whose name is specified as a String), in append mode.
Use FileOutputStream with append boolean value as true eg new FileOutputStream("C:/concat.txt", true));
Example
public class FileCOncatenation {
static public void main(String arg[]) throws java.io.IOException {
PrintWriter pw = new PrintWriter(new FileOutputStream("C:/concat.txt", true));
File file2 = new File("C:/Text/file2.rxt");
System.out.println("Processing " + file2.getPath() + "... ");
BufferedReader br = new BufferedReader(new FileReader(file2
.getPath()));
String line = br.readLine();
while (line != null) {
pw.println(line);
line = br.readLine();
}
br.close();
// }
pw.close();
System.out.println("All files have been concatenated into concat.txt");
}
}

Categories