2012-04-22 73 views
0

而不必經過700-800行文字的,每條線爲的一些變化:解析大約700行文本,將行分割並將它們用作變量?

-5,-8,0:2.0 

我有一種方法我要通過每一行,這是anotherclass.setBlock(xCoord, yCoord, zCoord, id)。因此,對於上面的例子,那就是:

anotherclass.setBlock(x-5, y-8, 0, 2); 

有沒有辦法通過文字的每一行解析和做到這一點?我一直在尋找年齡,這是要麼因爲我找不到正確的方式來說這個或我根本找不到答案)

我試過手動做,但100後線條,它開始覺得效率很低。由於座標不是連續的(或者說,它們是,但僅限於1或2行),所以我無法真正使用循環。

回答

5
import static java.lang.Double.parseDouble; 
import static java.lang.Integer.parseInt; 
import static java.util.regex.Pattern.compile; 

... 

public static void main(String[] args) { 
    BufferedReader r = null; 
    try { 
    r = new BufferedReader(new InputStreamReader(
     new FileInputStream("myfile.txt"), "UTF-8")); 
    final Pattern p = compile("(.+?),(.+?),(.+?):(.+)"); 
    String line; 
    while ((line = r.readLine()) != null) { 
     final Matcher m = p.matcher(line); 
     if (!m.matches()) 
     throw new RuntimeException("Line in invalid format: " + line); 
     anotherclass.setBlock(parseInt(m.group(1)), parseInt(m.group(2)), 
      parseInt(m.group(3)), parseDouble(m.group(4))); 
    } 
    } 
    catch (IOException e) { throw new RuntimeException(e); } 
    finally { try { if (r != null) r.close(); } catch (IOEXception e) {} } 
} 
相關問題