开发者

Read file and insert data into String[]

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开发者_JAVA技巧 to insert into the array. May someone help me figure out what I'm doing wrong here?


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();
        }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜