I have crated this method to read data from a text file. I am storing all the data which i recive from the BufferedReader inside a String array. Now when you want to read a specific data you have to pass the line number as argument to the method. The problem is i am getting data from line 2 but not able to get data from line 1. I am attaching the screen shot of the text file from where i am trying to read the data.
public String read(int num) throws IOException{
String readdata;
String[] data1=new String[20];
try {
FileReader read = new FileReader("E:\\TextFile.txt");
BufferedReader data = new BufferedReader(read);
while(data.readLine() != null){
for(int i=0; i<data1.length;i++){
data1[i]=data.readLine();
if(data1[i] == null){
break;
}//if
}//for
}//while
}//try
catch (FileNotFoundException e) {
e.printStackTrace();
}//catch
finally{
data.close();
}//finally
readdata=data1[num];
return readdata;
}//read
You are skipping the line :
while(data.readLine() != null){ // --> reading here
for(int i=0; i<data1.length;i++){
data1[i]=data.readLine(); //--> and here
You need to change your while
loop
String str="";
while((str=data.readLine()) != null){ // read the line
for(int i=0; i<data1.length;i++){
data1[i]=str; // and reuse it
if(data1[i] == null){
break;
}
}
}
What is the issue in your code? you are skipping first line.
while(data.readLine() != null){ // already reads first line here
for(int i=0; i<data1.length;i++){
data1[i]=data.readLine(); // now you are reading from 2nd line
if(data1[i] == null){
break;
}
}
}
You are in deed skipping the first line with the first data.readLine()
call.
You can simplify your loop like this:
for (int i = 0; i < data1.length && ((readData = data.readLine()) != null); i++) {
data1[i] = readData;
}
You can try this to avoid reading twice at the beginning:
String aux = data.readLine();
while(aux != null){
for(int i=0; i<data1.length;i++){
data1[i] = aux;
Hope it helps.
Clemencio Morales Lucas.
this might be a late response but may be it can help someone.
As per the steps followed in your code, you can try this as a solution:
int i=0;
while(data.ready()){
data1[i++] = data.readLine();
}
the ready() function will tell us whether the stream is available for reading. A buffered character stream is ready if the buffer is not empty, or if the underlying character stream is ready.
Hope that helps :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.