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:
- Imagine your file has more than 20 lines, so you'll try to access
liniiFisier[20]
, but this field is not present! Results inArrayIndexOutOfBounds
- In your
for
loop you are iteratingj
but always usingi
... - 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 ;-)
精彩评论