Originally Posted by
generalitico
What about to store it in a Vector
like this....
import java.util.Vector;
public static void ReadFile2String(String InputFile)
{
try{
FileInputStream fstream = new FileInputStream(InputFile);
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
text = "";
Vector myVector = new Vector();
while ((strLine = br.readLine()) != null) //loop through each line
{
myVector.add(strLine );
// Print the content on the console
text +=(strLine+"\n"); // Store the text file in the string
}
in.close();//Close the input stream
int i=0;
for(i=0;i<myVector.size();i++){
System.out.println("Position "+ i+" "+myVector.elementAt(i));
}
}
catch (Exception e)
{//Catch exception if any
System.out.println("Error: " + e.getMessage());
}
}
}
More of a pet-peeve than anything else, but usually when you declare a List (you have used a Vector in this case) you want to specify what type of Objects are in that list. This is just a way to make it easier to access the Objects, as you will not need to cast the objects when you get them. This is not as much of an issue when you use Lists of Strings, as they are easy to cast since their Object Representation is just a String of its value (sort of odd, and I'm unsure how to explain it).
However, this does become a problem if you had a Vector of Objects other than Strings. For example, a Vector of JFrames.
If you declared your Vector using the way you did:
Vector myVector = new Vector();, you would access the JFrames by saying:
Alternatively, if you declared your Vector to be restricted to only a Vector of JFrames like this:
Vector<JFrame> myVector = new Vector<JFrame>();, you would access the JFrames by saying:
JFrame frame = myVector.get(0);
So, the more acceptable way of creating your Vector above (acceptable meaning the general consensus of the programming community) would be saying:
Vector<String> myVector = new Vector<String>();
Once again, sort of a moot point when you have a Vector of Strings, but it is good advise to have on the back-burner for your future data structures. Tell me if I am unclear.