![](/img/trans.png)
[英]JSP(Java): Encoding byte array and use in JavaScript same in C#
[英]Byte[] Array to String C# to Java Without Encoding
這段C#代碼(據我所知)將byte []轉換為String而不使用編碼。 現在我試圖在Java中做同樣的事情,但我找不到合適的編碼來產生相同的結果。
TLDR:我正在尋找與下面的C#代碼產生相同結果的Java代碼/解決方案。
C#:
public static byte[] StringToByteArray(String value){
byte[] bytes = new byte[value.Length * sizeof(char)];
Buffer.BlockCopy(value.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
public static String ByteArrayToString(byte[] value){
char[] chars = new char[value.Length / sizeof(char)];
Buffer.BlockCopy(value, 0, chars, 0, value.Length);
return new string(chars);
}
public static byte[] StringToByteArray(String value){
return Encoding.UTF8.GetBytes(value)
}
public static String ByteArrayToString(byte[] value){
return Encoding.UTF8.GetString(value)
}
根據您的要求,這里是Java中等效代碼的一些示例...
基礎
// Converts the string using the default character encoding
// (equivalent of Encoding.Default in C#).
byte[] bytes = text.getBytes();
// Converts the string using the given character encoding, in this case UTF-8.
byte[] bytes = text.getBytes("UTF-8");
// Converts a byte array to a string using the default encoding.
String text = new String(bytes);
// Converts a byte array to a string using the given encoding.
String text = new String(bytes, "UTF-8");
代碼示例
public class EncodingTest {
public static void main(String[] args) {
try {
String originalText = "The quick brown fox jumped over the lazy dog.";
byte[] defaultBytes = originalText.getBytes();
byte[] utf8Bytes = originalText.getBytes("UTF-8");
byte[] utf16Bytes = originalText.getBytes("UTF-16");
byte[] isoBytes = originalText.getBytes("ISO-8859-1");
System.out.println("Original Text: " + originalText);
System.out.println("Text Length: " + originalText.length());
System.out.println("Default Bytes Length: " + defaultBytes.length);
System.out.println("UTF-8 Bytes Length: " + utf8Bytes.length);
System.out.println("UTF-16 Bytes Length: " + utf16Bytes.length);
System.out.println("ISO-8859-1 Bytes Length: " + isoBytes.length);
String newDefaultText = new String(defaultBytes);
String newUtf8Text = new String(utf8Bytes, "UTF-8");
String newUtf16Text = new String(utf16Bytes, "UTF-16");
String newIsoText = new String(isoBytes, "ISO-8859-1");
System.out.println("New Default Text: " + newDefaultText);
System.out.println("New UTF-8 Text: " + newUtf8Text);
System.out.println("New UTF-16 Text: " + newUtf16Text);
System.out.println("New ISO-8859-1 Text: " + newIsoText);
} catch (Exception e) {
e.printStackTrace();
}
}
}
對String構造更多信息在這里 。
和Java的一些進一步的教程編碼這里 。
正如我在評論中所說,字符串/字節轉換沒有“無編碼”之類的東西。 可能存在使用隱式或默認編碼,但是始終需要編碼才能將字符串轉換為字節[],反之亦然。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.