java.lang.NumberFormatException:空字符串 - OBJ Model Loader

时间:2013-07-15 13:15:07

标签: java regex opengl models

我想将OBJ模型加载到OpenGL中。但是我在获取有关模型的数据时遇到问题,当我读取文件时,我收到此错误:

Exception in thread "main" java.lang.NumberFormatException: empty String
    at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1011)
    at java.lang.Float.valueOf(Float.java:417)
    at game.trippylizard.OBJLoader.loadModel(OBJLoader.java:18)
    at game.trippylizard.MainScreen.<init>(MainScreen.java:39)
    at game.trippylizard.MainScreen.main(MainScreen.java:71)

这是我的OBJLoader类中的代码:

public class OBJLoader {
    public static Model loadModel(File f) throws FileNotFoundException, IOException {
        BufferedReader reader = new BufferedReader(new FileReader(f));
        Model m = new Model();
        String line;
        while ((line = reader.readLine()) != null) {
            if (line.startsWith("v ")) {
                float x = Float.valueOf(line.split(" ")[1]); //Error is here
                float y = Float.valueOf(line.split(" ")[2]);
                float z = Float.valueOf(line.split(" ")[3]);
                m.vertices.add(new Vector3f(x,y,z));
            } else if (line.startsWith("vn ")) {
                float x = Float.valueOf(line.split(" ")[1]);
                float y = Float.valueOf(line.split(" ")[2]);
                float z = Float.valueOf(line.split(" ")[3]);
                m.normals.add(new Vector3f(x,y,z));
            } else if (line.startsWith("f ")) {
                Vector3f vertexIndices = new Vector3f(
                        Float.valueOf(line.split(" ")[1].split("/")[0]), 
                        Float.valueOf(line.split(" ")[2].split("/")[0]),
                        Float.valueOf(line.split(" ")[3].split("/")[0])
                );

                Vector3f normalIndices = new Vector3f(
                        Float.valueOf(line.split(" ")[1].split("/")[2]), 
                        Float.valueOf(line.split(" ")[2].split("/")[2]),
                        Float.valueOf(line.split(" ")[3].split("/")[2])
                );

                m.faces.add(new Face(vertexIndices, normalIndices));
            }
        }
        reader.close();
        return m;
    }
}

有人可以告诉我如何解决这个问题吗?

P.S。我对正则表达式和那种格式都不熟悉。

1 个答案:

答案 0 :(得分:1)

您的模型Vertex定义行似乎在“v”指令后包含多一个空格。 你期待这个:

"v -1.0 1.0 1.0"

但模型包含:

"v    -1.0 1.0 1.0"

因此您的代码无法处理这种情况。

尝试解析如下:

    String arr[] = line.substring(2).trim().split(" ");

    float x = Float.parseFloat(arr[0]);
    float y = Float.parseFloat(arr[1]);
    float z = Float.parseFloat(arr[2]);
    m.vertices.add(new Vector3f(x,y,z));