2

I'm executing java code. readLine() method returns an empty string from a text file even when there is text in the file.

BufferedReader csv =  new BufferedReader(new FileReader("D:/SentiWordNet_3.0.0/home/swn/www/admin/dump/senti.txt"));
String line = "";      
while((line = csv.readLine()) != null){ 
    String[] data = line.split("\t");
    Double score = Double.parseDouble(data[2])-Double.parseDouble(data[3]);
}

After the split() is called, there is an exception thrown Arrayindexoutofboundsexception.
Below is the text file. Each line starts with "a" followed by a number. the code was able to retrieve the line with the word apocrine, but not the line with word eccrine. when I ran in debug mode, the line variable returned as empty string.

a 00098529 0 0 apocrine#1 (of exocrine glands) producing a secretion in which part of the secreting cell is released with the secretion; "mother's milk is one apocrine secretion"

a 00098736 0.25 0 eccrine#1 (of exocrine glands) producing a clear aqueous secretion without releasing part of the secreting cell; important in regulating body temperature

a 00098933 0 0 artesian#1 (of water) rising to the surface under internal hydrostatic pressure; "an artesian well"; "artesian pressure"

Should I use someother construct to read the lines from the text file

Community
  • 1
  • 1
ramya
  • 23
  • 1
  • 6

6 Answers6

1

You can see in javadoc of readline() in BufferedReader the following..

Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.

So, if you text consists with a line feed ('\n') followed by a carriage return, BufferedReader will return an empty String. Consider following String.

abc\n\rdef

This will return "abc", "", "def" if you call readLine() 3 times. Not only the above String, the following String may also cause the same result.

abc\n\ndef

abc\r\rdef

In your text file, it must have contain one or more of these combinations. Or it may contain whitespases between those special characters. As example:

abc\n\t\ndef

abc\n \rdef

and so on...

That's why you are getting an empty line.

To overcome this problem you can check whether the line is empty in the while-loop.

while ((line = csv.readLine()) != null) {
    if(line.trim().isEmpty()){
        continue;
    }
    //Your code
}
Community
  • 1
  • 1
Ramesh-X
  • 4,853
  • 6
  • 46
  • 67
0

Following is a sample method to read data from file.
Here after reading each line is added in to an arraylist and the arraylist is returned.

public ArrayList<String> fileRead(String fileName){
        File           f;
        String         s;
        FileReader     fr = null;
        BufferedReader br = null;
        ArrayList<String>   sl = new ArrayList<String>();
        try {
            f  = new File(fileName); 
            fr = new FileReader(f);
            br = new BufferedReader(fr);
            while((s=br.readLine())!=null){
                sl.add(s);
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
                try {
                    if(br!=null)
                        br.close();
                    if(fr!=null)
                        fr.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
        }
        return sl;
    }
Rakesh KR
  • 6,357
  • 5
  • 40
  • 55
  • 1
    Why a -1 value is given to this; it is right my friends.... I just write a method to read the data from the file and store it in an ArrayList – Rakesh KR Aug 30 '13 at 12:58
  • your answer suited my problem.it did not throw any errors and it was able to return me all the lines. thanks – ramya Aug 30 '13 at 13:46
0

Try using Scanner:

Scanner in = new Scanner(new FileReader("filename.txt"));
while (in.hasNext()){
   String str = in.next());
   // Use it
}
Learner
  • 1,503
  • 6
  • 23
  • 44
0

To read every line:

while ((thisLine = br.readLine()) != null) {
     System.out.println(thisLine);
   }

If this doesn't works then I assume you have a problem with the text file.

Emilio
  • 1,024
  • 4
  • 16
  • 33
  • thanks for the reply. this does not work. i guess its my file i have to take care of then – ramya Aug 30 '13 at 12:57
0
        //Get scanner instance
        Scanner scanner = new Scanner(new File("SampleCSVFile.csv"));

        //Set the delimiter used in file
        scanner.useDelimiter(",");

        //Get all tokens and store them in some data structure
        //I am just printing them
        while (scanner.hasNext()) 
        {
            System.out.print(scanner.next() + "|");
        }

        //Do not forget to close the scanner  
        scanner.close();
Dhrumil Shah
  • 736
  • 6
  • 15
-1

the key point is you use wrongly the BufferedReader, if you use the FileReader like

new FileReader( filename ) 

here the filename is the file path like "./data/myfile.txt". the ecplise or the compilier will not give a compiling error or warning, however, this is a fatal error that will lead to read nothing from the file if you then use readLine(). the correct way like this:

BufferedReader csv =  new BufferedReader(new FileReader( new File("filename") ) )
csv.readLine()

I tried your file, and find that your file format is wrong. your file format is follow: a 00098529 0 0 every string is separated by space but not tab, so when you use split("\t") you get nothing. given your file format, you should use split(" ") or you should change your file format by dividing each string with tab

  • thanks for the reply. i tried this way but still error exists – ramya Aug 30 '13 at 12:58
  • I tried your file, and find that your file format is wrong. your file format is follow: a 00098529 0 0 every string is separated by space but not tab, so when you use split("\t") you get nothing. given your file format, you should use split(" ") or you should change your file format by dividing each string with tab – lonerranger Aug 30 '13 at 13:19
  • is there a way i can upload my text file in this site because im not sure if copying it here really helps – ramya Aug 30 '13 at 13:30
  • you can add a image in your question to show your data format or write your file in the code area which will protect your file format. – lonerranger Aug 30 '13 at 13:47
  • here is a simple way to test whether the error is comes from the file format or something else. 1. create a file that contains a 00098529 0 0 each string is divided by a space. 2. create a file that contains a 00098529 0 0 each string is divided by tab. in convenience, you can use notepad++ ( a soft ware) to view your file. – lonerranger Aug 30 '13 at 14:07
  • im not sure why this happened, but when doing readLine somehow an empty line was created which throwed errors because of split method. so first i used arraylist to neatly store each line which also created the empty string in the arraylist but did not throw any errors and second make a check if the string is not empty before doing the split based on \t and then perform my score calculation. – ramya Aug 30 '13 at 14:29