convert .txt file in .csv format

Ads
 

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

Ads









Related Tutorials/Questions & Answers:
how to convert .xml file to csv file
how to convert .xml file to csv file  how to convert .xml file to csv file
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
Advertisements
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
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
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
convert data format sql
convert data format sql  convert data format sql
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
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
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
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
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
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
Backup Into txt File
Backup Into txt File       Backup Into txt File is used to put the backup file from a ... illustrate an example from 'Backup Into txt File'. To understand this example
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
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-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 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
Backup selected records into txt file
Backup selected records into txt file       Backup selected records into txt file is used to copies... into txt file. To restore the selected backup records into txt file, we create
.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
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
Backup Into txt File
Backup Into txt File       Backup Into txt File is used to put the backup file from... The Tutorial illustrate an example from 'Backup Into txt File
Java code to convert pdf file to word file
Java code to convert pdf file to word file  How to convert pdf file to word file using Java
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
How to convert XML file to database ?
How to convert XML file to database ?  How to convert XML file to database
how to convert a jar file into .exe file
how to convert a jar file into .exe file  hi, I want convert my jar file into executable file,urgently please help me
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 zip file to byte array
convert zip file to byte array  Hi,How to convert zip file to byte array,can you please provide program?? Thanks, Ramanuja

Ads