2013-03-23 21 views
1

我剛開始學習Java,對於我的第一個挑戰,我試圖從MP3中讀取ID3v1標記。我將一個MP3的最後128個字節讀入一個字節數組,然後從那裏分割出來。爲了檢查我發現了一個有效的ID3標籤,我將數組中的前3個字節轉換爲一個字符串,並將其與「TAG」進行比較。問題是由字節組成的字符串永遠不會匹配「TAG」字符串,即使它看起來應該在我在eclipse調試器中運行它的時候。Java - 將字節轉換爲字符串並與另一個字符進行比較

我粘貼了我在下面使用的代碼,任何人都可以請指出我在這裏做錯了什麼?

byte tagBytes[] = {84, 65, 71}; //Normally filed from a file, just here as an example. 
String tagHeader = null; //String to hold tag header 
tagHeader = Character.toString((char)tagBytes[0]) + 
      Character.toString((char)tagBytes[1]) + 
      Character.toString((char)tagBytes[2]); 
if (tagHeader != "TAG"){ 
    System.out.println("No ID3v1 tag found"); 
    return null; 
} 
+1

[如何比較字符串我[Java](http://stackoverflow.com/search?q=java+string+compare) – Eran 2013-03-23 21:52:16

回答

2

字符串不能被==,因爲這會檢查內存中的文字引用是相同的比較。取而代之的是做"TAG".equals(tagHeader)"TAG".equalsIgnoreCase(tagHeader)做一個不區分大小寫的比較。

您還可以簡化您的字符串的建築,像這樣:

StringBuilder sb = new StringBuilder(); 
for(int i = 0; i < 3; i++) { 
    sb.append((char)tagBytes[i]); 
} 
tagHeader = sb.toString(); 

甚至,作爲@Vulcan建議,簡單地說:

tagHeader = new String(tagBytes,0,3); 

你很可能需要指定字符集,以及否則字節可能會被錯誤地轉換。根據數據的編碼方式,您可能需要指定不同的字符集:

tagHeader = new String(tagBytes,0,3,Charset.forName("UTF-8")); 
+1

甚至'tagHeader = new String(tagBytes)'。 – Vulcan 2013-03-23 21:55:21

+0

好的電話,謝謝你的建議。 – dimo414 2013-03-23 22:11:40

0

變化tagHeader != "TAG"!tagHeader.equals("TAG")

目前,你是比較內存地址,而不是實際值。

爲了清楚起見,我是這樣寫的。對於空安全代碼,你應該總是首先使用字面值。

"TAG".equals(tagHeader) 
1

您可以轉換字節爲String,如果你確信它們都是ASCII(或者,如果你知道的編碼)。那麼你應該比較equals而不是!=,因爲稍後檢查它是否不是相同的實例。在你的情況下,它總是一個不同的例子。

byte tagBytes[] = {84, 65, 71}; 
    String tagHeader = new String(tagBytes, Charset.forName("US-ASCII")); 
    if (!"TAG".equals(tagHeader)){ 
     System.out.println("No ID3v1 tag found"); 
     return null; 
    } 

或者你可以避開只是這樣一共創建冗餘String對象:

byte tagBytes[] = {84, 65, 71}; 
    if (!('T' == tagBytes[0] && 'A' == tagBytes[1] && 'G' == tagBytes[2])){ 
     System.out.println("No ID3v1 tag found"); 
     return null; 
    } 
1

這會變成字節爲String和正確:

byte tagBytes[] = {84, 65, 71}; 
String s = new String(tagBytes, Charset.forName("US-ASCII")); 

您的解決方案也適用。這是你的比較,這是問題。你想:

if (!tagHeader.equals("TAG")) { 

在字符串的情況下,!===測試這兩個字符串是相同的實例,而不是相同的值。您需要使用equals()方法按值進行比較。

變種: 要選擇字節數組的只是一部分:

String s = new String(tagBytes, 0, 3, Charset.forName("US-ASCII")); 

如果整個字節數組已轉換爲字符串,你想看看,如果它不與「TAG」啓動:

if (!tagHeader.startsWith("TAG")) { 
1
以簡單的方式,你可以做

如下:

public static void main(String[] args) { 
    byte tagBytes[] = {84, 65, 71}; //Normally filed from a file, just here fro example. 
    String tagHeader = null; //String to hold tag header 
    tagHeader = new String(tagBytes); 
    if (!tagHeader.equals("TAG")){ 
     System.out.println("No ID3v1 tag found"); 
    } 
} 
相關問題