开发者

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开发者_StackOverflow中文版 = 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]);    


Change that last line to

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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜