raj
convert .txt file in .csv format
1 Answer(s)      5 years and 2 months ago
Posted in : Java Beginners
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.
Advertisement
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
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
Convesion of txt file to doc file.??????
Convesion of txt file to doc file.??????  how to convert text file to doc file using java
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
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 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
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
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.
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
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
convert data format sql
convert data format sql  convert data format sql
.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
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... into txt file. To restore the selected backup records into txt file, we create
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 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
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
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
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: Example import java.io.*; import java.util.*; public
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
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
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... a Page ("ReadCsvFile.jsp") to retrieve the data from CSV file "
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
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
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
SQL Bulk Insert csv
respectively.Again, we create a file abc  with extension csv contain the records... SQL Bulk Insert csv       SQL Bulk Insert is used to import the records from csv  file