0
public static String[] words = null;

public static String readFile(String name) {
    int i = 0;
    try {
        BufferedReader br = new BufferedReader(new FileReader(name));
        try {
            StringBuilder sb = new StringBuilder();
            String line = br.readLine();

            while (line != null) {
                i++;
                sb.append(sb.toString());
                sb.append("\n");
                line = br.readLine();
            }
            String everything = sb.toString();
            words = everything.split("\\n");//not sure if this is right...
        } finally {
            br.close();
        }
    } catch (Exception e) {
        e.getMessage();
    }
    return "Loaded " + i + " words";
}

I'm basically trying to read a file with data on each line. On each line in the file I'm trying to insert into the array. May someone help me figure out what I'm doing wrong here?

1 Answer 1

7

The problem is that:

  while (line != null) {
            i++;
            sb.append(sb.toString());
            sb.append("\n");
            line = br.readLine();
        }

sb is never actually appended anything, it is just appending empty strings over and over again.

should be:

  while (line != null) {
            i++;
            sb.append(line);
            sb.append("\n");
            line = br.readLine();
        }
Sign up to request clarification or add additional context in comments.

Comments

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.