Program:
package JavaCoders;
import java.io.*;
/**
*
* @author B
*/
class Csv_Read
{
public static void main(String[] arg)
{
char a[]=new char[100];
try
{
String f1="H:\\JavaCoders\\wingsofm.csv";
FileReader fr=new FileReader(f1);
fr.read(a);
for(char s:a)
{
System.out.print(s);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
In this program, the file to be read is in csv format. csv stands for comma separated values.In this file the values are separated by commas to differentiate the fields.You must have to import java.io.* package as we have to use FileReader. First we have to create array of character type, you can give it size according to your need.After that store the path of your file to the string type datatype. Then create the object of FileReader, you have to pass the string variable which contains path of the file into this object. FileReader object is use to read the data from the file. It will read the file character by character. After FileReader object read all the data from the file and it will place the data into the array or the data will be store into the array indices of char type.Now we have to read the data from the char[] array. For this we can use for each loop to iterate the array.In for each loop the data form the array index is set to the "s" variable which is of character type. Then there is System.out.println statement which will print the value contained in the variable.One important thing that must be remember is that we must place our code into try and catch block otherwise it will generate the compile time exception. The output of the program is given below:
OUTPUT:

No comments:
Post a Comment