Java基础 实验七 文件操作
一、实验内容
1)编程:求2~200之间的所有素数,将求得的结果保存到PRIME.DAT文件中。
2)编程:检查C盘根目录下CONFIG..SYS文件是否存在,若在则显示该文件的名称和内容。
3)编程:输入5个学生的信息(包含学号、姓名、3科成绩),统计各学生的总分,然后将学生信息和统计结果存入二进制数据文件STUDENT.DAT中。
4)编程:从第(3)题中建立的STUDENT.DAT文件中读取数据,寻找平均分最高的学生,并输出该学生的所有信息。
二、实验代码
package exceptionseven;
import java.io.*;
public class ExceptionSeven {
/**
* 问题一
* 求2~200之间的所有素数,将求得的结果保存到PRIME.DAT文件中
*/
public void One() throws FileNotFoundException, IOException {
FileOutputStream fos = new FileOutputStream("D:\\PRIME.DAT");
int temp = 2;
fos.write(String.valueOf(temp).getBytes());
fos.write(" ".getBytes());
temp = 3;
fos.write(String.valueOf(temp).getBytes());
fos.write(" ".getBytes());
for(int i = 3; i <= 100; i++) {
for(int j = 2; j <= i/2; j++) {
if(i%j == 0) {
break;
}
if(j == i/2) {
//System.out.println("100以内素数:" + i);
fos.write(String.valueOf(i).getBytes());
fos.write(" ".getBytes());
}
}
}
fos.close();
}
/**
* 问题二
* 检查C盘根目录下CONFIG..SYS文件是否存在,
* 若在则显示该文件的名称和内容。
*/
public void Two() throws FileNotFoundException, IOException {
String filePath1 = "C:\\CONFIG.SYS" ;
String filePath2 = "D:\\users.txt";
String filePath3 = "D:\\PRIME.DAT";
File fi = new File(filePath3);
if(fi.exists()) {
System.out.println("文件名称为:" + fi.getName());
FileInputStream fis = new FileInputStream(fi);
byte[] data = new byte[(int)fi.length()];
fis.read(data);
fis.close();
String msg = new String(new String(data));
System.out.println("文件内容为:");
System.out.println(msg);
} else {
System.out.println("文件不存在");
}
}
public void ThreeAndFour() throws FileNotFoundException, IOException {
//五名学生的信息:
int i, j;
int sum = 0;
String[] Sno = {"123", "456", "789", "147", "258"};
String[] Name = {"zhangSan", "liSi", "wangWu", "lixiao", "niNing"};
double[][] Score = {{56, 58, 99}, {45, 88, 65}, {12, 74, 54}, {12, 56, 54}, {85, 74, 54}};
double[] sumScore = new double[5];
for (i = 0; i < 5; i++) {
for(j = 0; j < 3; j++) {
sum += Score[i][j];
}
sumScore[i] = sum;
sum = 0;
}
//五名学生的学号、姓名、总成绩存入文件中
String filePath = "D:\\STUDENT.DAT" ;
File file = new File(filePath);
OutputStream fos = new FileOutputStream(file);
DataOutputStream dos = new DataOutputStream(fos);
for(i = 0; i < 5; i++) {
dos.writeUTF(Sno[i]);
dos.writeUTF(Name[i]);
dos.writeDouble(sumScore[i]);
}
dos.close();
//读取数据
String[] newSno = new String[5];
String[] newName = new String[5];
double[] newSum = new double[5];
InputStream fis = new FileInputStream(file);
DataInputStream dis = new DataInputStream(fis);
for(i = 0; i < 5; i++) {
newSno[i] = dis.readUTF();
newName[i] = dis.readUTF();
newSum[i] = dis.readDouble();
System.out.print(newSno[i] + " " + newName[i] + " ");
System.out.printf("%.1f\n",newSum[i]/3.0);
}
dis.close();
}
public static void main(String[] args) throws IOException {
ExceptionSeven exec = new ExceptionSeven();
exec.One();
exec.Two();
exec.ThreeAndFour();
}
}