Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to read a file?

 
shippu devaraju
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a text file which contains one e-mail address per line.
what i want to do is i want to read each line of the text file from a java file and store this emails in a String array of that java file.
can any body sujest what classes and functions of I/O package i have to use.
Thanks in advance
 
Michael Morris
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you have a file formatted by one line per record, your best bet is to use something that extends the Reader class. In this case I would use a FileReader wrapped in a BufferedReader thus:

Then loop thru the file calling the readLine() method on your BufferedReader which returns a String.
Now the trick here is how do you know ahead of time how many Strings you're going to end up with?
The answer is you don't need to know, just create a Vector (Vector strings = new Vector()) and using the add(Object o) method from the Vector class put each string read into the container.
Finally, the Vector class has a method toArray(Object[] oArray) to extract your Strings but don't forget to cast it back to a String[].
 
Roy Ben Ami
Ranch Hand
Posts: 732
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
here is something that i wrote:
import java.io.*;
import java.util.*;
public class Ranch
{
// the streams we will use
static FileReader fr;
static BufferedReader in;
public static void main(String args[])
{
// your file
File file=new File("email.txt");
//opens a reader to it
try{
fr=new FileReader(file);}
catch(FileNotFoundException e){System.out.println("file not found");}
//opens a bufferdReader to read lines!
in=new BufferedReader(fr);
//each line will be stored here
String email;
// an arraylist to hold all the strings
ArrayList emails=new ArrayList();
//reads the lines!
try{
while((email=in.readLine())!=null)
{
emails.add(email);
}
}
catch(IOException e){System.out.println("Error while reading!");}
//whatever happens close the streams
finally{
try{
in.close();
fr.close();
}
catch(IOException e){System.out.println("Exception closing files");}
}

//converts the arraylist to an array
Object myArray[]=emails.toArray();
//displays the array to check it
for(int i=0;i<myArray.length;i++)
System.out.println(myArray[i]);
}
}
 
shippu devaraju
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
Mr.Michael Morris and Mr.Roy Ben Ami Thank you For Your replies.I appriciate your pations in explaning solution.
You guys really saved my Time greatly.
bye
shippu
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic