J2ME将文本文件读入String数组

时间:2012-12-05 14:56:12

标签: string file-io java-me

请指出我的代码中的错误在哪里?

我有一个简单的文本文件,其中包含以下数据结构:

something1
something2
something3
...

结果为String[],其中每个元素都是文件的最后一个元素。我找不到错误,但在line.setLength(0);

附近出错了

有什么想法吗?

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 个答案:

答案 0 :(得分:3)

我看到一个明显错误 - 您在StringBuffer中多次存储相同的Vector个实例,并使用StringBuffer清除相同的setLength(0)个实例。我猜你想要做这样的事情

 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
 ...

答案 1 :(得分:-1)

如果您的问题是在String []中读取文件的内容,那么您实际上可以使用apache common的FileUtil类并读入数组列表然后转换为数组。

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

在您指定的代码中,您可以重新初始化StringBuffer,而不是将length设置为0。

相关问题