比较Java中具有不同字节顺序掩码的字符串

在我的Java程序中,我有两个字符串,s1并且s2在打印时它们看上去都相等,但是,因为它们的编码方式不同,所以s1.equals(s2)返回false。我将如何比较这两个字符串,以便即使它们的编码方式不同,它们仍然相等?


看下面的示例代码:


    s1 = s1.trim();

    s2 = s2.trim();

    byte[] s1bytes = s1.getBytes();

    byte[] s2bytes = s2.getBytes();

    System.out.println(s1+","+s2+","+s1.equals(s2));


    System.out.println("\ns1's bytes are:");

    for (int i = 0; i < s1bytes.length; i++) {

        System.out.println(s1bytes[i]);

    }


    System.out.println("\ns2's bytes are:");

    for (int i = 0; i < s2bytes.length; i++) {

        System.out.println(s2bytes[i]);

    }

打印:


SHEOGMIOF,SHEOGMIOF,false


s1's bytes are:

-17

-69

-65

83

72

69

79

71

77

73

79

70


s2's bytes are:

83

72

69

79

71

77

73

79

70

正如你可以看到打印时s1和s2看起来是一样的,相比当他们不相等的两个字节数组是不同的。


编辑:我的问题不同于此问题,因为我不是从文件中读取数据,.java文件中的源代码编码方式不同,而不是其他文件中的数据编码。


慕妹3146593
浏览 206回答 2
2回答

HUWWW

从文件中读取字符串时,请从字符串中删除字节顺序掩码(BOM)。的字符代码是"\uFEFF"public class Foo {&nbsp; &nbsp; public static void main(final String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; final byte[] b1 = {-17, -69, -65, 83, 72, 69, 79, 71, 77, 73, 79, 70};&nbsp; &nbsp; &nbsp; &nbsp; final byte[] b2 = {83, 72, 69, 79, 71, 77, 73, 79, 70};&nbsp; &nbsp; &nbsp; &nbsp; final String s1 = new String(b1).replace("\uFEFF", "");&nbsp; &nbsp; &nbsp; &nbsp; final String s2 = new String(b2).replace("\uFEFF", "");&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(s1);&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(s2);&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(s1.equals(s2));&nbsp; &nbsp; }}印刷:SHEOGMIOFSHEOGMIOFtrue
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java