1. In the io package, two platform-independent data operation flows are provided
DataOutputStream
Data InputStream
2. Usually, the data output stream will output the data in a certain format, and then read the data in a certain format through the data input stream.
(1)DataOutputStream
package org.example.io;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class TestDataOutputStream {
public static void main(String[] args) throws IOException { // throw all exceptions
DataOutputStream dos = null; // declare data output stream object
File f = new File("e:\\s\\test \\a.txt"); // file save path
dos = new DataOutputStream(new FileOutputStream(f)); // instantiate data output stream object
String[] names = {"shirt", "glove", "scarf "}; // item name
float[] prices = {98.3f, 30.3f, 50.5f}; // item price
int[] nums = {3, 2, 1}; // item quantity
for (int i = 0 ; i < names.length; i++) {
dos.writeChars(names[i]); // output string
dos.writeChar('\t'); // output delimiter
dos. writeFloat(prices[i]); // output price
dos.writeChar('\t');
dos.writeInt(nums[i]); // output quantity
dos.writeChar('\n');
}
dos.flush();
dos.close() ;
}
}
(2)DataInputStream
package org.example.io;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class TestDataInputStream {
public static void main(String[] args) {
DataInputStream dis = null; // declare data input stream object
File f = new File("e:\\s\\test\\a.txt"); // read file path
try {
dis = new DataInputStream(new FileInputStream(f)); // instantiate data input stream object
String name = null; // receive name
float price = 0.0f; // receive price
int num = 0; / / Received quantity
char[] temp = null; // Received product name
int len = 0; // Save the number of read data
char c = 0; // '\u0000'
while (true) {
temp = new char[ 200]; // open up space
len = 0;
while ((c = dis.readChar()) != '\t') { // 单个字符地循环读取商品名称
temp[len] = c;
len++;
}
name = new String(temp, 0, len); // 商品名称
price = dis.readFloat(); // 读取价格
dis.readChar(); // 读取\t
num = dis.readInt(); // 读取数量
dis.readChar(); // 读取\n
System.out.println("Name:"+name+"\t\tPrice:"+price+"\tNum:"+num);
}
} catch (FileNotFoundException e2) {
e2.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (dis != null) {
try {
dis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}