2011-02-08 42 views
0

在java中,我想快速解析一個文件,其中包含異質數據(數字和字符)。java,ByteBuffer來解析文件中的數據

我一直在閱讀關於ByteBuffer和內存映射文件。

我可以複製它,但是當解析數據時它變得棘手。我想分配不同的字節。但它變得依賴於編碼?

如果該文件的格式,例如:

someString 8
some other string 88

我怎樣才能解析它以StringInteger對象?

謝謝!

Udo。

+1

如果順序訪問和閱讀「文字」和「保存爲文本整數」是主要的用例,那麼我會用緩衝A *啓動*讀者爲基地。 ByteBuffer對某些事物有好處。這通常不是。 – 2011-02-08 20:44:33

回答

2

假設你的格式是一樣的東西

{string possibly with spaces} {integer}\r?\n 

你需要搜索換行符,直到找到第一空間落後工作。你可以自己解碼這個數字,並把它變成一個int或者把它變成一個String並解析它。除非必須,否則我不會使用Integer。現在您知道行的起始位置和整數的起始位置,您可以將字符串提取爲字節,並使用所需的編碼將其轉換爲字符串。

這假定換行符和空格在編碼中是一個字節。如果它們是多字節字節,它仍然可以完成將會更加複雜。

編輯:下面的例子打印...

text: ' someString', number: 8 
text: 'some other string', number: -88 

代碼

ByteBuffer bb = ByteBuffer.wrap(" someString 8\r\nsome other string -88\n".getBytes()); 
while(bb.remaining()>0) { 
    int start = bb.position(),end, ptr; 
    for(end = start;end < bb.limit();end++) { 
     byte b = bb.get(end); 
     if (b == '\r' || b == '\n') 
      break; 
    } 
    // read the number backwards 
    long value = 0; 
    long tens = 1; 
    for(ptr = end-1;ptr>= start;ptr--) { 
     byte b = bb.get(ptr); 
     if (b >= '0' && b <= '9') { 
      value += tens * (b - '0'); 
      tens *= 10; 
     } else if (b == '-') { 
      value = -value; 
      ptr--; 
      break; 
     } else { 
      break; 
     } 
    } 
    // assume separator is a space.... 
    byte[] bytes = new byte[ptr-start]; 
    bb.get(bytes); 
    String text = new String(bytes, "UTF-8"); 
    System.out.println("text: '"+text+"', number: "+value); 

    // find the end of the line. 
    if (bb.get(end) == '\r') end++; 
    bb.position(end+1); 
} 
1

你可以試試這樣說:

CharacterIterator it = new StringCharacterIterator(StringBuffer.toString()); 
for (char c = it.first(); c != CharacterIterator.DONE; c = it.next()) { 
    if (Character.isDigit(c)) { 
     // character is digit 
    } else { 
     // character is not-digit 
    } 
} 

或者如果你喜歡

String str = StringBuffer.toString(); 
String numbers = str.replaceAll("\\D", ""); 
String letters = str.replaceAll("\\W", ""); 

然後,你需要在你的字符串numbers執行Integer.parseInt()照常上的字符,你可以使用正則表達式。

+0

謝謝,但我正在尋找更具體的ByteBuffer實現。 – ssedano 2011-02-08 20:12:23

+0

ByteBuffer基於某些內容給出了「字符串」和「整數」? – 2011-02-08 20:19:27

0

您是否在尋找java.util.Scanner?除非你真的有異國情調的性能要求,這應該是足夠快:

Scanner s = new Scanner(new File("C:\\test.txt")); 
    while (s.hasNext()) { 
     String label = s.next(); 
     int number = s.nextInt(); 

     System.out.println(number + " " + label); 
    }