首页 > 代码库 > DataInputStream和DataOutputStream
DataInputStream和DataOutputStream
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class DataStream { public static void main(String[] args) throws IOException { // write("test5.txt"); // read("test5.txt"); readFromBuffer(writeToBuffer()); } //write to local file public static void write(String path) throws IOException{ DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(path))); out.writeInt(1); out.writeShort(2); out.writeLong(1); out.writeUTF("Some text"); out.flush(); out.close(); } //read from local file public static void read(String path) throws IOException{ DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(path))); System.out.println(in.readInt()); System.out.println(in.readShort()); System.out.println(in.readLong()); System.out.println(in.readUTF()); in.close(); } //write to byte array public static byte[] writeToBuffer() throws IOException{ byte[] buff = null; ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream out = new DataOutputStream(new BufferedOutputStream(bos)); out.writeInt(1); out.writeShort(2); out.writeLong(1); out.writeUTF("Some text"); out.flush(); out.close(); buff = bos.toByteArray(); bos.close(); return buff; } //read from byte array public static void readFromBuffer(byte[] b) throws IOException{ DataInputStream in = new DataInputStream(new BufferedInputStream(new ByteArrayInputStream(b))); System.out.println(in.readInt()); System.out.println(in.readShort()); System.out.println(in.readLong()); System.out.println(in.readUTF()); in.close(); } }
DataInputStream和DataOutputStream
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。