国外java代码例子经典 国外java英文视频教程( 十 )


public void writeData(DataOutput out) throws IOException {
FixStringIO.writeFixString(name, NAME_LENGTH, out);
out.writeInt(age);
out.writeDouble(salary);
FixStringIO.writeFixString(married, MARRIED_LENGTH, out);
}
// 写入一条固定长度的记录到随机读取文件中 。
private void writeData(RandomAccessFile out) throws IOException {
FixStringIO.writeFixString(name, NAME_LENGTH, out);
out.writeInt(age);
out.writeDouble(salary);
FixStringIO.writeFixString(married, MARRIED_LENGTH, out);
}
// 随机写入一条固定长度的记录到输出流的指定位置 。
public void writeData(RandomAccessFile out, int n) throws IOException {
out.seek((n - 1) * RECORD_LENGTH);
writeData(out);
}
// 从输入流随机读入一条记录 , 即一个人的数据 。
private void readData(RandomAccessFile in) throws IOException {
name = FixStringIO.readFixString(NAME_LENGTH, in);
age = in.readInt();
salary = in.readDouble();
married = FixStringIO.readFixString(MARRIED_LENGTH, in);
}
// 从输入流随机读入指定位置的记录 。
public void readData(RandomAccessFile in, int n) throws IOException {
in.seek((n - 1) * RECORD_LENGTH);
readData(in);
}
}
// 对固定长度字符串从文件读出、写入文件
class FixStringIO {
// 读取固定长度的Unicode字符串 。
public static String readFixString(int size, DataInput in)
throws IOException {
StringBuffer b = new StringBuffer(size);
int i = 0;
boolean more = true;
while (moreisize) {
char ch = in.readChar();
i++;
if (ch == 0) {
more = false;
} else {
b.append(ch);
}
}
// 跳过剩余的字节 。
in.skipBytes(2 * (size - i));
return b.toString();
}
// 写入固定长度的Unicode字符串 。
public static void writeFixString(String s, int size, DataOutput out)
throws IOException {
int i;
for (i = 0; isize; i++) {
char ch = 0;
if (is.length()) {
ch = s.charAt(i);
}
out.writeChar(ch);
}
}
}
package IO;
import java.io.*;
import java.util.*;
public class FileRW {
// 需要输入的person数目 。
public static int NUMBER = 3;
public static void main(String[] args) {
Person[] people = new Person[NUMBER];
// 暂时容纳输入数据的临时字符串数组 。
String[] field = new String[4];
// 初始化field数组 。
for (int i = 0; i4; i++) {
field[i] = "";
}
// IO操作必须捕获IO异常 。
try {
// 用于对field数组进行增加控制 。
int fieldcount = 0;
// 先使用System.in构造InputStreamReader,再构造BufferedReader 。
BufferedReader stdin = new BufferedReader(new InputStreamReader(
System.in));
for (int i = 0; iNUMBER; i++) {
fieldcount = 0;
System.out.println("The number " + (i + 1) + " person");
System.out
.println("Enter name,age,salary,married(optional),please separate fields by ':'");
// 读取一行 。
String personstr = stdin.readLine();
// 设置分隔符 。
StringTokenizer st = new StringTokenizer(personstr, ":");
// 判断是否还有分隔符可用 。
while (st.hasMoreTokens()) {
field[fieldcount] = st.nextToken();
fieldcount++;
}
// 如果输入married , 则field[3]不为空,调用具有四个参数的Person构造函数 。
if (field[3] != "") {
people[i] = new Person(field[0],
Integer.parseInt(field[1]), Double
.parseDouble(field[2]), field[3]);
// 置field[3]为空,以备下次输入使用 。
field[3] = "";
}
// 如果未输入married,则field[3]为空,调用具有三个参数的Person构造函数 。

推荐阅读