This week's book giveaway is in the Agile and other Processes forum. We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line! See this thread for details.
i have a text file with n number of lines. I want to read that file and write into an array. How can i do that? I don't know the size of the file, how can i get the size? can i use VECTOR? If any body has source code or somebody can write code,please pass it on to me. text file as follows wille,programmer dan,team lead mike,analyst,programmer My code is String thisLine1; FileInputStream fin1 = new FileInputStream("first.txt"); DataInputStream myInput1 = new DataInputStream(fin1); while ((thisLine1 = myInput1.readLine()) != null) { where do i go from here? Thanks in advance.
You can use any of the Collections objects like a Vector, Array List or a list. You do not need to know the length of the file prior to creation of these structures.
Originally posted by suresh kamsa: i have a text file with n number of lines. I want to read that file and write into an array. How can i do that? I don't know the size of the file, how can i get the size? can i use VECTOR? If any body has source code or somebody can write code,please pass it on to me. text file as follows wille,programmer dan,team lead mike,analyst,programmer My code is String thisLine1; FileInputStream fin1 = new FileInputStream("first.txt"); DataInputStream myInput1 = new DataInputStream(fin1); while ((thisLine1 = myInput1.readLine()) != null) { where do i go from here? Thanks in advance.
David Cole
Greenhorn
Joined: Mar 07, 2001
Posts: 5
posted
0
Heres a sample that basically does just what you are looking for: import java.util.*; import java.io.*; public class FileToArray { public FileToArray() { } public String[] doIt(){ String fileName = "D:\\file.txt"; ArrayList lineList = new ArrayList(); BufferedReader reader = null; try{ reader= new BufferedReader( new FileReader(new File(fileName))); } catch(FileNotFoundException fnfe){ System.out.println("Unable to find the file: " + fileName); } try{ String currentLine = ""; while( (currentLine = reader.readLine()) != null) lineList.add(currentLine); } catch(IOException ioe){ ioe.printStackTrace(); } finally{ try{ if(reader != null) reader.close(); } catch(IOException ioe) { /* Do Nothing */ } } return (String[])lineList.toArray(new String[0]); } public static void main(String[] args) { FileToArray fileToArray = new FileToArray(); String[] lines = fileToArray.doIt(); if(lines != null){ System.out.println("Printing file contents:"); for(int i = 0; i < lines.length; i++){ System.out.println(lines[i]); } } } }