Stormel
Stormel

Reputation: 143

Problem reading from file

so i'm trying to read from a file a number of lines, and after that put them in a String[]. but it doesn't seem to work. what have i done wrong?

     String[] liniiFisier=new String[20];
    int i=0;
    try{
          FileInputStream fstream = new FileInputStream("textfile.txt");
          DataInputStream in = new DataInputStream(fstream);
          BufferedReader br = new BufferedReader(new InputStreamReader(in));
          String strLine;
          while ((strLine = br.readLine()) != null)   {
              liniiFisier[i]=strLine;
              i++;
          }
          //Close the input stream
          in.close();
            }catch (Exception e){//Catch exception if any
          System.err.println("Error: " + e.getMessage());
            }
            for(int j=0;j<i;j++)
                System.out.println(liniiFisier[i]);    

Upvotes: 1

Views: 164

Answers (2)

binfalse
binfalse

Reputation: 518

You should tell us what's happening and what problem occurred.

But I yet see some errors:

  1. Imagine your file has more than 20 lines, so you'll try to access liniiFisier[20], but this field is not present! Results in ArrayIndexOutOfBounds
  2. In your for loop you are iterating j but always using i...
  3. Creating the BufferedReader can be done in less code:

 

FileReader fr = new FileReader ("textfile.txt");
BufferedReader br = new BufferedReader (fr);

Since I don't know about your particular problem this might not solve it, so please provide more information ;-)

Upvotes: 1

Mat
Mat

Reputation: 206669

Change that last line to

System.out.println(liniiFisier[j]);  // important: use j, not i

Upvotes: 3

Related Questions