Java中将字节数组转换为Writer的程序
字节数组可以看作是字节和数组的组合。字节是最小的整数类型,数组是一种线性数据结构,用于存储相同数据类型的元素组。本文将讨论一个在Java中将字节数组转换为Writer的程序。让我们首先了解字节数组和Writer的概念。
字节数组和Writer类
字节数组
这是一种数组,用于存储字节类型数据的序列。我们将使用`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
结论
我们首先定义了字节数组及其声明语法。然后,我们了解了Writer类的基本概念,最后,我们讨论了两个将字节数组转换为Writer的Java程序示例。
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP