package testone;

import java.io.*;
public class fileread
{
    private String[] a = new String[100];
    String x;
    String sh;

    public void read(){


        try {
            // Open the file that is the first
            // command line parameter
            FileInputStream fstream = new FileInputStream("test.txt");
            // Get the object of DataInputStream
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine;
            //Read File Line By Line
            //for(int i=0;i<7;i++){
                while ((strLine = br.readLine()) != null) {
                    // Print the content on the console
                    
					/////I WANT TO SAVE each line of text to an ARRAY then access it from main by giving ARRAYNAME[3]
              

                }

           // }

            //Close the input stream
            in.close();
        } catch (Exception e) { //Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }
    }
        

   public static void main(String args[])  {
      fileread file = new fileread();
      file.read();
     
	 //** WHAT I WANT TO DO IS TO READ A LINE OF TEXT which is saved in array
	 //** i want to simply access it as arrayname[6]


  }
}

What i want to do is to access a line of text by saving it on to an array in the READ() -method .. and later access each line by giving its array position from main() method .. eg: array_Name[6]

please help me with the possible code

Recommended Answers

All 2 Replies

The line read is in the strLine variable. Since you have already defined your array, you can simply put that value inside the array. Of course within each while-loop run you will need to increase the index of the array so you will put the next line to the next element of the array.

Create a public method that takes as argument an int and returns the element of the array at that place, and call it from main. You need to do that because you have defined the array as private which I think is a good idea.

You do not need that "for" loop.
My suggestion is to just initialize a counter example :-
"lineCounter=0", just before the "while". And in the "while" block just put the following line :-

a[lineCounter++] = strLine;

That should do it.

<EDIT>
Shucks I guess javaAddict beat me to it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.