从文本文件中获取格式化数字的简便方法?

时间:2011-04-14 16:37:40

标签: java string text numbers

所以我在C ++中知道我可以这样做:

ifstream file("data/maps/ssdebug1.cfg");
    string line;
float startx = 0;
    sscanf (line.c_str(), "start-x = %f;", &startx);

但在Java中有同样简单的方法吗?

2 个答案:

答案 0 :(得分:2)

在Java中你可以做到

FileInputStream fis = new FileInputStream("data/maps/ssdebug1.cfg");
Properties prop = new Properties();
prop.load(fis);
fis.close();

// you can have any number of properties with comments. 
// However, it is not assumed aline ends with a ';'
String start_x = prop.getProperty("start-x");
double startx = Double.parseDouble(start_x);

答案 1 :(得分:1)

从java Version 1.5你也可以使用java.util.Scanner ..
http://download.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html

示例:

 Scanner in = new Scanner(new File("data/maps/ssdebug1.cfg"));
      while (in.hasNextLong()) {
          long my = in.nextLong();
      }