批處理風格中,每個處理步驟是一個單獨的程序;每一步必須在前一步結束後才能開始;數據必須是完整的,以整體的方式傳遞。
批處理風格基本組件是獨立的程序,鏈件鍵是某種類型的媒質。
程序示例如下:
【功能】:程序1實現隨機生成0到100內的6個數,並存儲到“Data.dat”文件中;程序2實現從“Data.dat”文件中讀取數據並輸出。
程序1:
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class sender {
static File tempFile = new File("Data.dat");
public static void main(String[] args) {
if (tempFile.exists()) {
System.out.println("文件Data.dat已經存在!");
System.exit(0);
}
outNumber();
}
public static void outNumber() {
DataOutputStream out = null;
try {
out = new DataOutputStream(new BufferedOutputStream(
new FileOutputStream(tempFile)));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
for (int i = 0; i < 6; i++)
try {
out.writeInt((int) (Math.random() * 100));
} catch (IOException e) {
e.printStackTrace();
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
程序2:
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileInputStream;
import java.io.IOException;
public class receiver {
static File tempFile = new File("Data.dat");
public static void main(String[] args) {
if (!tempFile.exists()) {
System.out.println("文件Data.dat不存在!");
System.exit(0);
}
getNumber();
}
public static void getNumber() {
DataInputStream in = null;
try {
in = new DataInputStream(new BufferedInputStream(
new FileInputStream(tempFile)));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
for (int i = 0; i < 6; i++)
try {
System.out.print(" " + in.readInt());
} catch (IOException e) {
e.printStackTrace();
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
對於以上程序,組件是程序1和程序2,連接件是Data.dat文件。