1

Could you please point out where is the bug in my code?

I have a simple text file with the following data structure:

something1
something2
something3
...

It results a String[] where every element is the last element of the file. I can't find the mistake, but it goes wrong somewhere around the line.setLength(0);

Any ideas?

public String[] readText() throws IOException {
    InputStream file = getClass().getResourceAsStream("/questions.txt");
    DataInputStream in = new DataInputStream(file);

    StringBuffer line = new StringBuffer();
    Vector lines = new Vector();

    int c;
    try {
        while( ( c = in.read()) != -1 ) {
            if ((char)c == '\n') {
                if (line.length() > 0) {
                    // debug
                    //System.out.println(line.toString());
                    lines.addElement(line);
                    line.setLength(0);
                }
            }
            else{
                line.append((char)c);
            }
        }
        if(line.length() > 0){
            lines.addElement(line);
            line.setLength(0);
        }

        String[] splitArray = new String[lines.size()];
        for (int i = 0; i < splitArray.length; i++) {
            splitArray[i] = lines.elementAt(i).toString();
        }
        return splitArray;

    } catch(Exception e) {
        System.out.println(e.getMessage());
        return null;
    } finally {
        in.close();
    }
}

2 Answers 2

3

I see one obvious error - you're storing the same StringBuffer instance multiple times in the Vector, and you clear the same StringBuffer instance with setLength(0). I'm guesing you want to do something like this

 StringBuffer s = new StringBuffer();
 Vector v = new Vector();

 ...
 String bufferContents = s.toString();
 v.addElement(bufferContents);
 s.setLength(0);
 // now it's ok to reuse s
 ...
Sign up to request clarification or add additional context in comments.

Comments

-1

If your problem is to read the contents of the file in a String[], then you could actually use apache common's FileUtil class and read in an array list and then convert to an array.

List<String> fileContentsInList = FileUtils.readLines(new File("filename"));
String[] fileContentsInArray = new String[fileContentsInList.size()];
fileContentsInArray = (String[]) fileContentsInList.toArray(fileContentsInArray);

In the code that you have specified, rather than setting length to 0, you can reinitialize the StringBuffer.

1 Comment

sorry, i didn't quite understand this idea. as far as i know generics aren't supported in javame.

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.