Java Io(数据输入输出流)
Java Io 字节流中的DataInputStream 和 DataOutputStream,使用流更加方便,是流的一个扩展,更方便读取int, long,字符等类型数据。
事例代码如下:
package com.dcz.io; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class DataStream { /** * 数据输入流事例 * @throws IOException */ public static void readData() throws Exception{ File file = new File("demo.txt"); if(!file.exists()){ throw new IllegalAccessException("文件不存在!"); } InputStream fileInputStream = new FileInputStream(file); DataInputStream dataInputStream = new DataInputStream(fileInputStream); // 读取数据 System.out.println(dataInputStream.readInt()); System.out.println(dataInputStream.readFloat()); System.out.println(dataInputStream.readInt()); System.out.println(dataInputStream.readDouble()); System.out.println(dataInputStream.readUTF()); System.out.println(dataInputStream.readChar()); System.out.println(dataInputStream.readChar()); System.out.println(dataInputStream.readChar()); dataInputStream.close(); } /** * 数据输出流事例 * @throws IOException */ public static void writeData() throws IOException{ File file = new File("demo.txt"); if(!file.exists()){ file.createNewFile(); } OutputStream fileOutputStream = new FileOutputStream(file); DataOutputStream dataOutputStream = new DataOutputStream(fileOutputStream); dataOutputStream.writeInt(300); dataOutputStream.writeFloat(12.38f); dataOutputStream.writeInt(-220); dataOutputStream.writeDouble(10.5); dataOutputStream.writeUTF("我们都是中国人"); dataOutputStream.writeChars("英国人"); dataOutputStream.close(); // 16进制形式显示 InputStream fileInputStream = new FileInputStream(file); int bytes = 0; while((bytes = fileInputStream.read()) != -1){ System.out.print(Integer.toHexString(bytes) + ","); } fileInputStream.close(); System.out.println(""); System.out.println("文件写入完毕!"); } public static void main(String[] args) throws Exception { // 写数据 DataStream.writeData(); // 读数据 DataStream.readData(); } }