当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java ObjectOutputStream writeShort()用法及代码示例


ObjectOutputStream类writeObject()方法

  • writeObject() 方法可在java.io包。
  • writeObject() 方法用于写入给定的 2 字节短值。
  • writeObject() 方法是一个非静态方法,它只能通过类对象访问,如果我们尝试使用类名访问方法,那么我们将得到一个错误。
  • writeObject() 方法可能会在写短时抛出异常。
    IOException:在写入输出流时出现任何输入/输出错误时,可能会抛出此异常。

用法:

    public void writeShort(int value);

参数:

  • int value– 表示一个整数,表示要写入的短值。

返回值:

该方法的返回类型是void,它什么都不返回。

例:

// Java program to demonstrate the example 
// of void writeShort(int value) method of 
// ObjectOutputStream

import java.io.*;

public class WriteShortOfOOS {
 public static void main(String[] args) throws Exception {
  // Instantiates ObjectOutputStream , ObjectInputStream 
  // FileInputStream and 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);

  // By using writeShort() method is to
  // write the short to the stream		
  obj_out_stm.writeShort(100);
  obj_out_stm.writeShort(124);
  obj_out_stm.writeShort(168);
  obj_out_stm.writeShort(152);

  obj_out_stm.flush();

  // By using readShort() method is to 
  // read the int and convert it into short
  for (int i = 0; i < 4; ++i) {
   short sh = (short) obj_in_stm.readShort();
   System.out.println("obj_in_stm.readShort():" + sh);
  }

  // By using close() method is to 
  // close all the streams 
  System.out.println("Stream Shutdown... ");

  file_in_stm.close();
  file_out_stm.close();
  obj_in_stm.close();
  obj_out_stm.close();
 }
}

输出

obj_in_stm.readShort():100
obj_in_stm.readShort():124
obj_in_stm.readShort():168
obj_in_stm.readShort():152
Stream Shutdown... 


相关用法


注:本文由纯净天空筛选整理自Preeti Jain大神的英文原创作品 Java ObjectOutputStream writeShort() Method with Example。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。