Java 将字节数组转换为写入器
字节数组可以说是字节和数组的组合。字节是最小的整数类型,数组是一种线性数据结构,用于存储相似数据类型的元素组。本文将讨论Java中将字节数组转换为写入器的程序。让我们首先了解字节数组和写入器这两个术语。
字节数组和写入器类
字节数组
它是一种存储字节数据序列的数组类型。我们将使用”getBytes()”方法将指定的字符串转换为字符序列,并将它们存储在字节数组中。
语法
byte[] nameOfarray;
// declaration
Or,
byte nameOfarray[];
// declaration
Or,
// declaration with size
byte nameOfarray[] = new byte[sizeofarray];
// declaration and initialization
byte nameOfarray[] = {values separated with comma};
我们可以在我们的程序中使用上述任何一种语法。
Writer类
这是一个表示字符流的类。在本文中,我们将使用它的子类之一名为’StringWriter’的类,该类用于获得字符串的字符流。此外,为了将元素插入到Writer类的对象中,我们将使用它的内置方法’append()’。
语法
Writer nameOfObject = new StringWriter();
将字节数组转换为Writer的程序
示例1
以下示例演示了将字节数组转换为Writer类的过程。
方法
- 定义一个带参数的自定义方法名为’printWr()’,用于将字节数组转换为Writer。
-
在此方法内部,创建一个’Writer’类的对象,并使用’try’块使用’append()’方法将元素插入到writer类对象中。
-
然后,使用’toString()’方法返回存储在对象中的值。这个方法将对象的值转换为字符串形式。
-
现在,在’main()’方法内部,声明和初始化两个变量,并使用’getBytes()’方法将它们转换为字节数组。
-
最后,调用’printWr()’方法,并将字节数组作为参数传递。
import java.io.*;
public class ByteWr {
// method to convert byte array to writer
String printWr(byte[] data1, byte[] data2) {
Writer newWr = new StringWriter();
// object of writer class
try {
// appending data to obejct of writer class
newWr.append(new String(data1) );
newWr.append(new String(data2) );
newWr.close();
} catch (Exception exp) {
// to handle exception
System.out.println(exp);
}
// returning values of object in the form of string
return newWr.toString();
}
public static void main(String args[]) {
ByteWr wrt = new ByteWr();
// create object of ByteWr class
String st = "Tutorial";
char chs = 's';
// storing values into byte array
byte data1[] = st.getBytes();
byte data2[] = Character.toString(chs).getBytes();
// calling method to pass byte array to writer
System.out.println("Byte Array using Writer: " + wrt.printWr(data1, data2) );
}
}
输出
Byte Array using Writer: Tutorials
示例2
这是另一个示例,演示了将字节数组转换为 writer 类的过程。
方法
- 声明并初始化两个字节数组。
-
定义一个‘Writer’类的对象。
-
在 try 块中,使用‘append()’方法将两个字节数组插入‘Writer’类的对象中。
-
现在,使用 toString 方法调用对象内的‘println()’方法。
import java.io.*;
public class ByteWr {
public static void main(String[] args) {
// declare two byte array
byte info1[] = "Tutorials".getBytes();
byte info2[] = "Point".getBytes();
// define object of writer class
Writer newWr = new StringWriter();
try {
// to add data to writer object
newWr.append(new String(info1));
newWr.append(new String(info2));
newWr.close();
} catch (IOException exp) {
// to handle exception
System.out.println(exp);
}
// calling object of writer class
System.out.println("Byte Array using Writer: " + newWr.toString());
}
}
输出
Byte Array using Writer: TutorialsPoint
结论
我们在本文中首先对字节数组及其声明语法进行了定义。然后,我们理解了写入类的基本概念,最后讨论了两个将字节数组转换为写入类的Java程序示例。