convert .txt file in .csv format

convert .txt file in .csv format

Dear all,

I hope you are doing good.
I am looking to convert .txt file in .csv format.
The contents might have different names and values.
e.g.

start:
id:XXXX
name:abc
address:xyz

start:
age:29
height:5'9

start:
accountno:xxx
emailid:xxxxx

end:

I want export these contents to a .csv file. I am aware that I need to use delimiter. But I am not getting the exact out put I do wish to.
This is what I thought I should do.

1.look for the start:
2.once you catch first start:, look for the name:value pair using : delimiter.
3.store this name:value pair in local variable like string etc.
4.repeat the steps until we see end:
5.extract the name:value pair in a .csv file.

I am interested in message at console. At the same time, I also want the stored name:value pairs should be exported to .csv file and I should be able to display contents of the .csv file.

This is what I have written so far.
[code]
import java.util.regex.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;

public class fileRead
{
public static void main(String[] args)
{
File file = new File("C:\\source1.txt");
StringBuilder sb = new StringBuilder();
String line=null;


try
{
BufferedReader reader = new BufferedReader(new FileReader(file));
String text = null;

// repeat until all lines is read
while ((line = reader.readLine()) != null)
{
if(!line.trim().equals(""))
{
if(line.startsWith("begin:"))
{
String[] data = sb.toString().trim().split("\n");

for(String chunk : data)
{
String[] parts = chunk.split(":");
System.out.println(parts[0] + " : " + parts[1]);
}

sb.setLength(0);
}
else
{
sb.append(line).append("\n");
}
}
/*String splitarray[] = line.split(":");
String firstentry = splitarray[0];
String secondentry = splitarray[2];
System.out.println(firstentry + " " + secondentry);*/


}
} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
} finally
{
System.out.println("Out");
}
}

// show file contents here
//System.out.println(str.toString()); }
}

[/code]

it would be a great help if anyone has got idea for the flow control. Thanks in advance.
View Answers

March 11, 2010 at 4:50 PM

Hi Friend,

Try the following code:

import java.io.*;
import java.util.*;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;

public class TextToCSV {
public static void main (String[] args) throws Exception {
try{
FileInputStream fstream = new FileInputStream("C:\\data.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
ArrayList list=new ArrayList();
while ((strLine = br.readLine()) != null){
list.add(strLine);
}
String id="",name="",course="",deptt="";

Iterator itr;


HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("Excel Sheet");
HSSFRow rowhead = sheet.createRow((short)0);
rowhead.createCell((short) 0).setCellValue("Roll No");
rowhead.createCell((short) 1).setCellValue("Name");
rowhead.createCell((short) 2).setCellValue("Marks");
rowhead.createCell((short) 3).setCellValue("Grade");

int index=1;
for (itr=list.iterator(); itr.hasNext(); ){
String str=itr.next().toString();
String [] splitSt =str.split(" ");
for (int i = 0 ; i < splitSt.length ; i++) {
id=splitSt[0];
name=splitSt[1];
course=splitSt[2];
deptt=splitSt[3];
}
HSSFRow row = sheet.createRow((short)index);
row.createCell((short)0).setCellValue(id);
row.createCell((short)1).setCellValue(name);
row.createCell((short)2).setCellValue(course);
row.createCell((short)3).setCellValue(deptt);
index++;
}

FileOutputStream fileOut = new FileOutputStream("c:\\TextToCSV.xls");
wb.write(fileOut);
fileOut.close();
System.out.println("Data is saved in excel file.");
}
catch(Exception e){System.out.println(e);}
}
}

Thanks









Related Tutorials/Questions & Answers:
convert .txt file in .csv format - Java Beginners
convert .txt file in .csv format  Dear all, I hope you are doing good. I am looking to convert .txt file in .csv format. The contents might have... want export these contents to a .csv file. I am aware that I need to use
how to convert .xml file to csv file
how to convert .xml file to csv file  how to convert .xml file to csv file
Advertisements
Convert CSV to excel File - Java Beginners
Convert CSV to excel File  Sir, i have CSV file as input. I need to convert that CSV file to excel file and format. Currently i am using HSSF POI api to format the excel file. Here i am unable to read the data from the CSV
txt to cvs format
); //convert(outpath); } }   Java convert text file to CSV file... file from one directory and writes an new one in cvs format in another one. I am...(); } //this class converts the text file into binary static void convert(String to_convert
convert excel file data into different locales while converting exclile file to csv file
convert excel file data into different locales while converting exclile file to csv file   can any one provide the code for how to convert excel file data into different locales while converting exclile file to csv file
How to convert excel file int xml format in java
How to convert excel file int xml format in java  How to read excel file(xls) which is stored in any directory(D://) and convert it into xml format in java and place in any directory(E://).Can any body provide the code
Convesion of txt file to doc file.??????
Convesion of txt file to doc file.??????  how to convert text file to doc file using java
sir, how to convert excel file to csv file using java? please send me sample code.
sir, how to convert excel file to csv file using java? please send me sample code.  please send me sample code for converting excel file into csv file uisng java
Thread for reading txt file
Thread for reading txt file  how to use 3 thread to read 3 txt file? To create three threads for reading the file and three threads for getting the strings out of the queue and printing them. thanks
Uploading and download pdf or .txt file.
Uploading and download pdf or .txt file.  I want admin user to upload pdf file into database and the users can download those pdf format from database
How create csv format in jsf ?
the pdf file now I want to create .csv format using this data ? Please Help me...How create csv format in jsf ?  Dear Friends , Good morning to all of you? I have a problem to create .CSV format in jsf. Actully I have
Convert pdf to rtf and txt - XML
Convert pdf to rtf and txt  Can we convert PDF to RTF and TXT, and how?  Hi Friend, Try the following codes: 1)Convert PDF to RTF...) {} } } 2)Convert PDF to TEXT import java.io.*; import java.util.
convert data format sql
convert data format sql  convert data format sql
Backup Into txt File
Backup Into txt File       Backup Into txt File is used to put the backup file from a ... The Tutorial illustrate an example from 'Backup Into txt File
ModuleNotFoundError: No module named 'csv-convert'
ModuleNotFoundError: No module named 'csv-convert'  Hi, My Python... 'csv-convert' How to remove the ModuleNotFoundError: No module named 'csv-convert' error? Thanks   Hi, In your python environment
csv file download
csv file download  Hello Every one, when user clicks download button I want to retrieve data from mysql database table in csv format using java.if you know please send code. Thanks in Advance   Please visit
ModuleNotFoundError: No module named 'file_open_gips_txt'
ModuleNotFoundError: No module named 'file_open_gips_txt'  Hi, My... named 'file_open_gips_txt' How to remove the ModuleNotFoundError: No module named 'file_open_gips_txt' error? Thanks   Hi, In your
Shifting txt file to database - Java Beginners
Shifting txt file to database   Question Details: I want to shift data from txt file to Database. The data is written in the following text format. Record No. = 0001 Name : Abdul Rauf Designation
Backup selected records into txt file
Backup selected records into txt file       Backup selected records into txt file is used to copies... Selected records into txt file. To restore the selected backup records into txt
convert current date into date format
convert current date into date format  How to get current date and convert into date format in Java or PHP
.csv file to databse
.csv file to databse  I have an 1 .csv file.. its having the url values like http://maps.google.com/?q=425+Bingeman+Centre+Drive%2c+chrompet%2c+ON%2c+600+006... q is request parameter .425 Bingeman Centre Drive is address
Backup Into txt File
Backup Into txt File       Backup Into txt File is used to put the backup file from..._TO_REPLACE_1 The Tutorial illustrate an example from 'Backup Into txt File
how to change file from .txt to .mat(matrix)
how to change file from .txt to .mat(matrix)  i have a big file.txt and i want to change this file to file.mat(matrix) ...this is in windows not on any os ..thx if u answering quickly please
ModuleNotFoundError: No module named 'convert-csv-to-json'
ModuleNotFoundError: No module named 'convert-csv-to-json'  Hi, My... named 'convert-csv-to-json' How to remove the ModuleNotFoundError: No module named 'convert-csv-to-json' error? Thanks   Hi
ModuleNotFoundError: No module named 'convert-csv-to-xlsx'
ModuleNotFoundError: No module named 'convert-csv-to-xlsx'  Hi, My... named 'convert-csv-to-xlsx' How to remove the ModuleNotFoundError: No module named 'convert-csv-to-xlsx' error? Thanks   Hi
ModuleNotFoundError: No module named 'convert-csv-to-json'
ModuleNotFoundError: No module named 'convert-csv-to-json'  Hi, My... named 'convert-csv-to-json' How to remove the ModuleNotFoundError: No module named 'convert-csv-to-json' error? Thanks   Hi
ModuleNotFoundError: No module named 'convert-csv-to-xlsx'
ModuleNotFoundError: No module named 'convert-csv-to-xlsx'  Hi, My... named 'convert-csv-to-xlsx' How to remove the ModuleNotFoundError: No module named 'convert-csv-to-xlsx' error? Thanks   Hi
How to convert EBCDIC format value into ASCII format value in java
How to convert EBCDIC format value into ASCII format value in java  how to convert EBCDIC data format into ASCII format data using java Use Case:I my file contains ASCII format values as well as EBCDIC format values.I need
How to write into CSV file in Java
How to write into CSV file in Java  How to write into CSV file in Java   Hi, To create Comma separated value(CSV) file is very simple and the CSV file stores the value in the tabular form i.e. rows and columns
How to import txt file using SQL
How to import txt file using SQL  Hai, I have a log file in .txt format and format of the log is given below. From the log i want to pick up some particular words and insert onto a table using SQL. I want the output of the table
Remove JTable row that read txt file records
Remove JTable row that read txt file records  Hi every one. i have a jtable that correctly read data frome file and show them in own. I want to add a "Delete" button that when select a row and clicked button, row must deleted
Backup selected records into txt file
Backup selected records into txt file       Backup selected records into txt file is used... a Example from Backup Selected records into txt file. To restore the selected backup
convert JPG format to Binary formart - IDE Questions
convert JPG format to Binary formart  How can i convert JPG format to Binary format in visual basic ? is there any code for that can work? thanks Mohamad
Convert a Character into the ASCII Format
Convert a Character into the ASCII Format       In this section, you will learn to convert... the functionality to convert the  character data into the ASCII format Description
problem while reading .csv file
problem while reading .csv file  I have a problem here..... i am reading a .csv extention file which has some value....but the problem is der is an amount column which contains , in between (eg) 3,899.00 which inturns creates
Retrieve Data from CSV file in JSP
Retrieve Data from CSV file in JSP       CSV file : A CSV file is commonly known as a Comma Delimited File or a Character Separated File. It is a text file that has
Java Write To File CSV
Java Write To File CSV In this tutorial you will learn how to write to file... that is in a tabular form. In java to create a csv file is simple, you would require... a simple example which will demonstrate you how to write to csv file. To achieve
Java Read CSV file
Java Read CSV file In this tutorial, you will learn how to read csv file. CSV... to break the line using ",". The delimiter for a CSV file is a comma.... Here is a csv file:ADS_TO_REPLACE_1 Example import java.io.*; import
converting one file format to another
converting one file format to another  Hi ser I need a code to export data from data grid to PDF and XL format plz help me out
How to convert date to UTC format in Java?
How to convert date to UTC format in Java?  Hi, What is UTC Date format and How to convert date to UTC format in Java? I need simple to learn... java.util.GregorianCalendar; import java.util.TimeZone; /* How to convert date to UTC format
SQL Bulk Insert csv
respectively.Again, we create a file abc  with extension csv contain... into a table 'stu'.The LOAD DATA INFILE import the file abc.csv to the same format table... SQL Bulk Insert csv      
Convert Text File to PDF file
Convert Text File to PDF file  Here is the way how to covert your Text file to PDF File, public class TextFileToPDF { private static void... BufferedReader(new FileReader( "**INPUT FILE**")); String inLine
upload a file into database and progrm should support excel and text and csv file formats
upload a file into database and progrm should support excel and text and csv file formats  Hai all, I need a program to upload a file into database table... and the program should support .excel ,.txt ,.csv file formats. can
Convert Text File to PDF file
Convert Text File to PDF file  import java.io.BufferedReader; import... FileReader( Input File)); String inLine = null... FileOutputStream( output file)); document.open(); document.add
convert a file .doc to .zip
convert a file .doc to .zip  hiii, I uploaded a file...;TITLE>Display file upload form to the user</TITLE></HEAD> <...;td><b>Choose the file To Upload:</b></td> <td><
reading a csv file from a particular row
reading a csv file from a particular row  how to read a csv file from a particular row and storing data to sql server by using jsp servlet
How to select only .txt file to be zipped using java?
How to select only .txt file to be zipped using java?  Hello, i'm trying to zipp .txt files from a folder but i want to know how to select only .txt...() { public boolean accept(File dir, String name) { return !name.startsWith(".txt
Mysql Date Format Convert
Mysql Date Format Convert     ... and time. Now, we help you to convert the Mysql Date Format Conversion into other... an example 'Mysql Date Format Convert'. To grasp this concept we use Date now
parse a file into primitive binary format
parse a file into primitive binary format  Hi, I need help converting an audio file or any other file to its primitive binarty format, and when I read the inputstream I find it some integers and I don't know its binary
Export Database table to CSV File
Export Database table to CSV File In this tutorial, you will learn how to retrieve data from database and save it to CSV File. The Comma-separated values, better knows as CSV is having a delimited data format. It has field/columns

Ads