读取文件并将数据插入String []

时间:2011-07-07 15:58:31

标签: java arrays file-io

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";
}

我基本上是在尝试读取每行数据的文件。在我试图插入数组的文件中的每一行。有人可以帮我弄清楚我在这里做错了吗?

1 个答案:

答案 0 :(得分:7)

问题在于:

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

sb实际上从不附加任何东西,它只是一遍又一遍地附加空字符串。

应该是:

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