1

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]);    
3
  • what do you mean by "doesn't seem to work"? Commented Jun 18, 2011 at 10:25
  • it reads correctly the number of lines...but the text is not saved Commented Jun 18, 2011 at 10:26
  • 1
    As a side note, you will get an ArrayIndexOutOfBoundsException if the file has more than 20 lines. Commented Jun 18, 2011 at 10:30

2 Answers 2

3

Change that last line to

System.out.println(liniiFisier[j]);  // important: use j, not i
Sign up to request clarification or add additional context in comments.

Comments

1

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 ;-)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.