/** @version 1.11 2004-05-11 @author Cay Horstmann */import java.io.*; import java.util.*;public class RandomFileTest { public static void main(String[] args) { Employee[] staff = new Employee[3]; staff[0] = new Employee("Carl Cracker", 75000, 1987, 12, 15); staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1); staff[2] = new Employee("Tony Tester", 40000, 1990, 3, 15); try { // save all employee records to the file employee.dat DataOutputStream out = new DataOutputStream(new FileOutputStream("employee.dat")); for (Employee e : staff) e.writeData(out); out.close();
// retrieve all records into a new array RandomAccessFile in = new RandomAccessFile("employee.dat", "r"); // compute the array size int n = (int)(in.length() / Employee.RECORD_SIZE); Employee[] newStaff = new Employee[n]; // read employees in reverse order for (int i = n - 1; i >= 0; i--) { newStaff[i] = new Employee(); in.seek(i * Employee.RECORD_SIZE); newStaff[i].readData(in); } in.close();
// print the newly read employee records for (Employee e : newStaff) System.out.println(e); } catch(IOException e) { e.printStackTrace(); } } }class Employee { public Employee() {} public Employee(String n, double s, int year, int month, int day) { name = n; salary = s; GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day); hireDay = calendar.getTime(); } public String getName() { return name; } public double getSalary() { return salary; } public Date getHireDay() { return hireDay; } /** Writes employee data to a data output @param out the data output */ public void raiseSalary(double byPercent) { double raise = salary * byPercent / 100; salary += raise; } public String toString() { return getClass().getName() + "[name=" + name + ",salary=" + salary + ",hireDay=" + hireDay + "]"; } /** Writes employee data to a data output @param out the data output */ public void writeData(DataOutput out) throws IOException { DataIO.writeFixedString(name, NAME_SIZE, out); out.writeDouble(salary); GregorianCalendar calendar = new GregorianCalendar(); calendar.setTime(hireDay); out.writeInt(calendar.get(Calendar.YEAR)); out.writeInt(calendar.get(Calendar.MONTH) + 1); out.writeInt(calendar.get(Calendar.DAY_OF_MONTH)); } /** Reads employee data from a data input @param in the data input */ public void readData(DataInput in) throws IOException { name = DataIO.readFixedString(NAME_SIZE, in); salary = in.readDouble(); int y = in.readInt(); int m = in.readInt(); int d = in.readInt(); GregorianCalendar calendar = new GregorianCalendar(y, m - 1, d); hireDay = calendar.getTime(); } public static final int NAME_SIZE = 40; public static final int RECORD_SIZE = 2 * NAME_SIZE + 8 + 4 + 4 + 4; private String name; private double salary; private Date hireDay; }class DataIO { public static String readFixedString(int size, DataInput in) throws IOException { StringBuilder b = new StringBuilder(size); int i = 0; boolean more = true; while (more && i < size) { char ch = in.readChar(); i++; if (ch == 0) more = false; else b.append(ch); } in.skipBytes(2 * (size - i)); return b.toString(); } public static void writeFixedString(String s, int size, DataOutput out) throws IOException { int i; for (i = 0; i < size; i++) { char ch = 0; if (i < s.length()) ch = s.charAt(i); out.writeChar(ch); } } }
@version 1.11 2004-05-11
@author Cay Horstmann
*/import java.io.*;
import java.util.*;public class RandomFileTest
{
public static void main(String[] args)
{
Employee[] staff = new Employee[3]; staff[0] = new Employee("Carl Cracker", 75000, 1987, 12, 15);
staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
staff[2] = new Employee("Tony Tester", 40000, 1990, 3, 15); try
{
// save all employee records to the file employee.dat
DataOutputStream out = new DataOutputStream(new FileOutputStream("employee.dat"));
for (Employee e : staff)
e.writeData(out);
out.close();
// retrieve all records into a new array
RandomAccessFile in = new RandomAccessFile("employee.dat", "r");
// compute the array size
int n = (int)(in.length() / Employee.RECORD_SIZE);
Employee[] newStaff = new Employee[n]; // read employees in reverse order
for (int i = n - 1; i >= 0; i--)
{
newStaff[i] = new Employee();
in.seek(i * Employee.RECORD_SIZE);
newStaff[i].readData(in);
}
in.close();
// print the newly read employee records
for (Employee e : newStaff)
System.out.println(e);
}
catch(IOException e)
{
e.printStackTrace();
}
}
}class Employee
{
public Employee() {} public Employee(String n, double s, int year, int month, int day)
{
name = n;
salary = s;
GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day);
hireDay = calendar.getTime();
} public String getName()
{
return name;
} public double getSalary()
{
return salary;
} public Date getHireDay()
{
return hireDay;
} /**
Writes employee data to a data output
@param out the data output
*/
public void raiseSalary(double byPercent)
{
double raise = salary * byPercent / 100;
salary += raise;
} public String toString()
{
return getClass().getName()
+ "[name=" + name
+ ",salary=" + salary
+ ",hireDay=" + hireDay
+ "]";
} /**
Writes employee data to a data output
@param out the data output
*/
public void writeData(DataOutput out) throws IOException
{
DataIO.writeFixedString(name, NAME_SIZE, out);
out.writeDouble(salary); GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(hireDay);
out.writeInt(calendar.get(Calendar.YEAR));
out.writeInt(calendar.get(Calendar.MONTH) + 1);
out.writeInt(calendar.get(Calendar.DAY_OF_MONTH));
} /**
Reads employee data from a data input
@param in the data input
*/
public void readData(DataInput in) throws IOException
{
name = DataIO.readFixedString(NAME_SIZE, in);
salary = in.readDouble();
int y = in.readInt();
int m = in.readInt();
int d = in.readInt();
GregorianCalendar calendar = new GregorianCalendar(y, m - 1, d);
hireDay = calendar.getTime();
} public static final int NAME_SIZE = 40;
public static final int RECORD_SIZE = 2 * NAME_SIZE + 8 + 4 + 4 + 4; private String name;
private double salary;
private Date hireDay;
}class DataIO
{
public static String readFixedString(int size, DataInput in)
throws IOException
{
StringBuilder b = new StringBuilder(size);
int i = 0;
boolean more = true;
while (more && i < size)
{
char ch = in.readChar();
i++;
if (ch == 0) more = false;
else b.append(ch);
}
in.skipBytes(2 * (size - i));
return b.toString();
} public static void writeFixedString(String s, int size, DataOutput out)
throws IOException
{
int i;
for (i = 0; i < size; i++)
{
char ch = 0;
if (i < s.length()) ch = s.charAt(i);
out.writeChar(ch);
}
}
}
public void testIo() throws Exception{
File file=new File("d:/file/src.txt"); //要读的文件
InputStream in=new FileInputStream(file);
FileOutputStream out=new FileOutputStream ("d:/file/target.txt");//要写入的文件
byte[] b=new byte[1024];
while((in.read(b))!=-1){ //等于-1说明文件已读完
out.write(b); //写入到文件
}
System.out.println("success...");
in.close();
out.close();
}
//产生一个1000个5位以下的随机整数,并将它写如“rand.txt”内,之后输出这一千个数的最大最小值和平均值,并对这一千个数
//排序,保存在原文件中
import java.io.*;
class creat
{
public static void ct() throws IOException
{File f1=new File("rand.txt");
FileWriter fo=new FileWriter(f1);
BufferedWriter out=new BufferedWriter(fo);
for(int i=0;i<1000;i++)
{out.write(Integer.toString((int)(Math.random()*10000)));
out.newLine();
}
out.flush();
out.close();
fo.close();
}
}
class del
{public static void aver() throws IOException { File f1=new File("rand.txt");
FileReader fr=new FileReader(f1);
BufferedReader bfr=new BufferedReader(fr);
String s;long sum=0;int max,min,n;
sum=max=min=Integer.parseInt(bfr.readLine());
while((s=bfr.readLine())!=null)
{n=Integer.parseInt(s);
sum=n+sum;
if(n>max) max=n;
if(n<min) min=n;
}
System.out.println("最大值是:"+max);
System.out.println("最小值是:"+min);
System.out.println("平均数是:"+sum/1000);}
public static void paixu()
{}};public class file
{public static void main(String args[])
{try{creat.ct();
del.aver();}
catch(IOException e)
{}
}
}
//产生一个1000个5位以下的随机整数,并将它写如“rand.txt”内,之后输出这一千个数的最大最小值和平均值,并对这一千个数
//排序,保存在原文件中
import java.io.*;
class creat
{
public static void ct() throws IOException
{File f1=new File("rand.txt");
FileWriter fo=new FileWriter(f1);
BufferedWriter out=new BufferedWriter(fo);
for(int i=0;i<1000;i++)
{out.write(Integer.toString((int)(Math.random()*10000)));
out.newLine();
}
out.flush();
out.close();
fo.close();
}
};
class deal
{public static void aver() throws IOException { File f1=new File("rand.txt");
FileReader fr=new FileReader(f1);
BufferedReader bfr=new BufferedReader(fr);
String s;long sum=0;int max,min,n;
sum=max=min=Integer.parseInt(bfr.readLine());
while((s=bfr.readLine())!=null)
{n=Integer.parseInt(s);
sum=n+sum;
if(n>max) max=n;
if(n<min) min=n;
}
System.out.println("最大值是:"+max);
System.out.println("最小值是:"+min);
System.out.println("平均数是:"+sum/1000);
fr.close();
bfr.close();}
public static void paixu() throws IOException
{File f1=new File("rand.txt");
File tempfile=new File("temp.txt");
FileReader fr1=new FileReader(f1);
BufferedReader bfr1=new BufferedReader(fr1);
FileWriter fr2=new FileWriter(tempfile);
BufferedWriter bfr2=new BufferedWriter(fr2);
String s=null;int a[]=new int[1000];int i=0,j=0,k=0;
while((s=bfr1.readLine())!=null)
{a[i]=Integer.parseInt(s);
i++;}
fr1.close();
bfr1.close();
f1.delete();
for(i=0;i<1000;i++)
for(j=0;j<1000-i-1;j++)
if(a[j]>a[j+1])
{k=a[j];
a[j]=a[j+1];
a[j+1]=k;
}
for(i=0;i<1000;i++)
{s=Integer.toString(a[i]);
bfr2.write(s);
bfr2.newLine();}
bfr2.flush();
bfr2.close();
fr2.close();
tempfile.renameTo(f1);
}};public class file
{public static void main(String args[])
{try{creat.ct();
deal.aver();
deal.paixu();}
catch(IOException e)
{}
}
}
特别感谢wbj00(),简单明了!