Share on Google+Share on Google+

alain ndayishimiye
txt to cvs format
3 Answer(s)      5 years and 3 months ago
Posted in : Java Beginners

i am writing a simple program that read a text file from one directory and writes an new one in cvs format in another one. I am running into a problem on how to correctly format it . for now this is what i have can someone help me.. thank you :)

first class:


/*this program reads files from inpath and writes them to outpath as a single txt file*/


public class ConcatenatedFiles {

static public void main(String arg[]) throws IOException  {

    System.out.println("about to read");
    threadrunner thr1, thr2;
    System.out.println("thread 1 startin");
    thr1 = new threadrunner();
    System.out.println("thread 2 startin");
    thr2 = new threadrunner();


//this class converts the text file into binary
static void convert(String to_convert){

    File file=new File(to_convert);
    boolean exists = file.exists();
    if (!exists) {
        // It returns false if File or directory does not exist
        System.out.println("the file or directory you are searching does not exist : " + exists);

        // It returns true if File or directory exists
        System.out.println("Status: "+to_convert+ " has been created .");



second class: package;

import; import; import; import; import; import; import; import java.util.Random;

public class threadrunner extends Thread{

/*the following are my inpath  which is the dir to the files to be read and the outpath which is the
dir for the out put text.*/

private int a;
static String inpath = "C:\\Users\\ndayala\\asc";
static String outpath = "C:\\Users\\ndayala\\bin\\bin.txt";

public threadrunner() { }

// public void start() { // for (int i = 1; i <= a; ++i){ // // System.out.println(getName() + " is " + i); // try{ // sleep(1000); // } // catch(InterruptedException e){} // } // }

public void reba() throws IOException{
    Random rn = new Random();   
    PrintWriter pw = new PrintWriter(new FileOutputStream(outpath ));// write to the outpath dir

    File file = new File(inpath);//files from the inpath
    File[] files = file.listFiles();//listFiles all file in inpath dir

    int rndom = rn.nextInt(files.length);
    for (int i = 0; i < files.length; i++) {
        System.out.println("Processing " + files[i].getPath() + "... ");
        BufferedReader br = new BufferedReader(new FileReader(files[i].getPath()));
        String line = br.readLine();

        while (line != null) {
            line = line.replace(" ","" ); 
            line = line.replace("mSOriginatingSMSinMSC","" );  
            line = line.replace("GSMPLMNCallDataRecord","" ); 
            line = line.replace("tAC","" ); 

            System.out.println("found it~~~~~~~~~~~~~~~~"+files[i]);
            char com =',';
            line = br.readLine();
    System.out.println("your file have been concatenaded into one file under directory "+outpath);



View Answers

January 11, 2012 at 11:21 AM

Java convert text file to CSV file

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 {
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){
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 [] splitSt =str.split(" ");
for (int i = 0 ; i < splitSt.length ; i++) {
HSSFRow row = sheet.createRow((short)index);

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

January 11, 2012 at 11:57 AM

how do i import the "import org.apache.poi.hssf." and my input file is different it looks something lik this:

i want to extract all that is on the right side only and print it in cvs.

thank you :)

January 11, 2012 at 12:38 PM

okay i downloaded the the jar file and it works can i get a sample of the data.txt so i can try it out

Related Tutorials/Questions & Answers:
txt to cvs format
txt to cvs format  i am writing a simple program that read a text file from one directory and writes an new one in cvs format in another one. I am running into a problem on how to correctly format it . for now this is what i have
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 different names and values. e.g. start: id:XXXX name:abc address:xyz
CVS  Which CVS are you used? What are the steps are you going to follow to deploy a code in server
CVS  Explain about control version system?   CVS is used... to "checkout" that collection. CVS also helps you if you are part of a group of people.... Unfortunately, if someone is using another editor, that safeguard will not work. CVS
cvs - CVS
cvs  can you please tell me how to work with cvs integrated with eclipse 3.2???   Hi friend, The goal of the CVS component is to provide the best CVS integration in the best IDE. Because the CVS plug-in includes
CVS  can Anyone please tell me how to work with cvs integrated with eclipse 3.2 ASAP. it's an urgent. I'll be highly obliged
What is CVS
What is CVS   hii, What is CVS ?   Hello, CVS is used to keep track of collections of files in a shared directory called "The Repository". Each collection of files can be given a "module" name, which is used
learn CVS
learn CVS  How i can use cvs in eclipse, How i can check in and cheack out my project
".txt" to sql with JDBC
".txt" to sql with JDBC  how to insert ".txt" into sql result[BLOB] with JDBC
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
what is tagging - CVS
what is tagging  what is tagging process,cvs vendors
.cvs file - JSP-Servlet
.cvs file  how can i update the contents of .cvs(coma seperated) file to database? reading of cvs file and insert each value in database.  how can i update the contents of .csv(coma seperated) file to database? reading
Tool In JAVA - CVS
Tool In JAVA  Hai this is JAGADHISH Iam learning cvs tool.If anybody have related material or examples for this CVS tool plz send me.Thank you(in advance).  Hi friend, For read more information to visit this link
Convesion of txt file to doc file.??????
Convesion of txt file to doc file.??????  how to convert text file to doc file using java
Adding .txt files in a given directory
Adding .txt files in a given directory  I want to read number of XML... tag value as one .txt file in a given directory? I have extracted tag values but plz help me how can I save each body tag as one .txt file and add in a directory
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
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
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 import*; import java.util.*; import com.lowagie.text.*; import
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
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
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
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
Java Spring Hibernate Struts Training What does core Java include? java What are some way to learn Java quickly? Is it required to learn Java before learning Java Script? Is it necessary to learn java script before learning PHP? Are HTML5 and Java Script boosts Java career? Is Java object oriented? Fingerprint application with Java Uninstall Oracle Virtual Box JSON to HashMap Free Java online Training I want example of Control Statement in Java ANSI Color Codes with Python Create a Program that Calculates Input What is difference between JDK,JRE and JVM? How to see ubuntu version on server? How to get Page Source in Selenium (WebDriver) using Java? The path to the driver executable must be set by the webdriver.gecko.driver system property parse data from a link in java Java Program Qns using BlueJ How to fix HAX Kernel Module Is Not Installed error? Installing Audacity Looking for code Logic to check track changes & Coments in MSWord, MSWordx, MSExcel, MSExcelx is ON/OFF Installing JDK on Mac SAX Parser exception ERROR 601 (42P00): Syntax error. Encountered Thread java.lang.NoClassDefFoundError: org/apache/commons/fileupload/FileItemFactory How to install Ubuntu 16.04 LTS? HttpServletRequest cannot be resolved to a type in eclipse - Solved Unhandled event loop exception GC overhead limit exceeded Spring Data jpa with apache phoenix Caused by: java.lang.IllegalArgumentException: Not a host:port pair: PBUF o.a.h.h.z.RecoverableZooKeeper - Possibly transient ZooKeeper, quorum= com.thinkaurelius.titan.diskstorage.hbase.HBaseStoreManager class not found com.thinkaurelius.titan.diskstorage.hbase.HBaseStoreManager not found How to download and install Java 8 on Windows? How to uninstall JDK 7? How to install gtk-doc-tools package in Ubuntu? How to install Oracle JDK 8 on Ubuntu? ejabberd_ctl.beam not found - Solved How to convert date to UTC format in Java? How to install autoconf, automake and libtool in Ubuntu 15.10? How to convert current date to mm dd yyyy format in Java? How to convert current date to dd mm yyyy format in Java? How to stop window closing in "internalFrameClosing" event. How to find list of all index in Neo4j? file location SASLError using PLAIN: not-authorized how to convert war file into .exe file using java code


Advertisement null