Java ObjectOutputStream writeByte()方法与示例
ObjectOutputStream类writeByte()方法
writeByte()方法在java.io包中可用。
writeByte()方法用于写入一个字节(即8位)。
writeByte()方法是一种非静态方法,只能通过类对象访问,如果尝试使用类名称访问该方法,则会收到错误消息。
writeByte()方法在写入字节时可能会引发异常。
IOException:在写入输出流时遇到任何输入/输出错误时,可能引发此异常。
语法:
public void writeByte(int value);
参数:
intvalue–表示要写入的字节的整数。
返回值:
该方法的返回类型为void,不返回任何内容。
示例
//Java程序演示示例
//writeByte(intvalue)方法
//ObjectOutputStream-
import java.io.*;
public class WriteByteOfOOS {
public static void main(String[] args) throws Exception {
//实例化ObjectOutputStream,ObjectInputStream-
//FileInputStream和FileOutputStream-
FileOutputStream file_out_stm = new FileOutputStream("D:\\includehelp.txt");
ObjectOutputStream obj_out_stm = new ObjectOutputStream(file_out_stm);
FileInputStream file_in_stm = new FileInputStream("D:\\includehelp.txt");
ObjectInputStream obj_in_stm = new ObjectInputStream(file_in_stm);
//通过使用writeByte()方法是
//将字节写入流
obj_out_stm.writeByte(65);
obj_out_stm.writeByte(97);
obj_out_stm.flush();
//通过使用readByte()方法是
//读取字节
byte b1 = (byte) obj_in_stm.readByte();
byte b2 = (byte) obj_in_stm.readByte();
System.out.println("obj_in_stm.readByte(): " + b1);
System.out.println("obj_in_stm.readByte(): " + b2);
//通过使用close()方法是
//关闭所有流
System.out.println("Stream Shutdown... ");
file_in_stm.close();
file_out_stm.close();
obj_in_stm.close();
obj_out_stm.close();
}
}输出结果
obj_in_stm.readByte(): 65 obj_in_stm.readByte(): 97 Stream Shutdown...