(1) 編寫一個程序,如果文件Exercisel_01.txt 不存在,就創(chuàng)建一個名為Exercisel_01.txt 的文件。向這個文件追加新數(shù)據(jù)。使用文本I/O將20個隨機生成的整數(shù)寫入這個文件。文件中的整數(shù)用空格分隔。
package 選實驗6;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
public class task1 {
public static void main(String[] args)
{
String fileName = "Exercise_01.txt";
//檢查文件是否存在,如果不存在則創(chuàng)建
File file = new File(fileName);
try {
if(!file.exists()) {
file.createNewFile();
System.out.println(fileName+"已創(chuàng)建。");
}
//寫入20個隨機數(shù)字
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName,true));
Random random = new Random();
for(int i=0;i<20;i++)
{
int num = random.nextInt();
//每個整數(shù)之間用空格隔開
writer.write(Integer.toString(num)+" ");
}
//關(guān)閉BufferWriter,確保資源被釋放
writer.newLine();
writer.close();
System.out.println(fileName+"已被寫入數(shù)據(jù)。");
//打開文件并讀取內(nèi)容和打印內(nèi)容
BufferedReader reader = new BufferedReader(new FileReader(file));
String lineString;
System.out.println(fileName+"里面的內(nèi)容為:");
while((lineString = reader.readLine())!=null)
{
System.out.println(lineString);
}
reader.close();
}
catch(IOException e) {
e.printStackTrace();
}
//刪除文件,以便能夠多次運行
if (file.delete()) {
System.out.println(fileName+"已刪除。" );
} else {
System.out.println(fileName+"無法刪除");
}
}
}
(2) 編寫一個程序,如果文件Exercisel_02.dat 不存在,就創(chuàng)建一個名為Exercisel_02.dat 的文件。向這個文件追加新數(shù)據(jù)。使用二進制I/O 將20個隨機生成的整數(shù)寫入這個文件中。利用二進制I/O讀取這個文件中的內(nèi)容并顯示。
package 選實驗6;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;
public class task2 {
public static void main(String[] args) {
String fileName = "Exercisel_02.dat";
//檢查文件是否存在,如果不存在則創(chuàng)建
File file = new File(fileName);
try {
if(!file.exists())
{
file.createNewFile();
System.out.println(fileName+"已創(chuàng)建。");
}
//寫入20個隨機數(shù)字
DataOutputStream dataOutputStream = new DataOutputStream(new FileOutputStream(fileName,true));
Random random = new Random();
for(int i=0;i<20;i++)
{
int num = random.nextInt();
//每個整數(shù)之間用空格隔開
dataOutputStream.writeInt(num);
}
//關(guān)閉DataOutputStream,確保資源被釋放
dataOutputStream.close();
System.out.println(fileName+"已被寫入數(shù)據(jù)。");
//打開文件并讀取內(nèi)容和打印內(nèi)容
DataInputStream dataInputStream = new DataInputStream(new FileInputStream(fileName));
System.out.println(fileName+"里面的內(nèi)容為:");
while(dataInputStream.available()>0)
{
int num = dataInputStream.readInt();
System.out.print(num+" ");
}
System.out.println();
dataInputStream.close();
}
catch (IOException e) {
e.printStackTrace();
}
//刪除文件,以便能夠多次運行
if (file.delete()) {
System.out.println(fileName+"已刪除。" );
} else {
System.out.println(fileName+"無法刪除");
}
}
}
(3) 對一個學(xué)生成績單進行讀寫操作。請直接下載blackboard上提供的data.txt文件作為數(shù)據(jù)源。具體要求如下:文章來源:http://www.zghlxwxcb.cn/news/detail-805023.html
- 新建一個可序列化的Student類,其中包括四個成員變量:int型學(xué)號、String類型學(xué)生名字、String類型學(xué)生所在學(xué)院、int型成績(參考data.txt文件)。重寫toString方法用于打印Student對象。
- 使用BufferedReader從data.txt文件中讀取數(shù)據(jù),并存放到一個集合對象中,要求按照學(xué)生名字的字母順序升序排列。
- 創(chuàng)建一個本地文件output.txt,將集合中的數(shù)據(jù)序列化到此文件中。(10分)
將output.txt中的數(shù)據(jù)反序列化,按照降序輸出所有成績在92分以上的學(xué)生信息;如果學(xué)生成績相同,則按照學(xué)生名字的字母順序降序輸出。文章來源地址http://www.zghlxwxcb.cn/news/detail-805023.html
package 選實驗6;
import java.io.*;
import java.util.*;
// 新建一個可序列化的Student類
// 實現(xiàn)Serializable 接口,用于可序列化類
// 實現(xiàn)Comparable接口,用于排序
class Student implements Serializable,Comparable<Student>{
// 保證在對象序列化和反序列化過程中確保版本一致性
private static final long serialVersionUID = 1L;
private int studentId;
private String studentName;
private String college;
private int grade;
// 構(gòu)造方法,用于創(chuàng)建Student對象
public Student(int studentId, String studentName, String college, int grade) {
this.studentId = studentId;
this.studentName = studentName;
this.college = college;
this.grade = grade;
}
// 重寫toString方法,用于打印Student對象信息
@Override
public String toString() {
String res;
res = "學(xué)生{" +
"學(xué)號:" + studentId +
"; 名字:" + studentName +
"; 學(xué)院:" + college +
"; 成績:" + grade +
'}';
return res;
}
// 實現(xiàn)Comparable接口的compareTo方法,用于按學(xué)生名字升序排列
@Override
public int compareTo(Student one) {
return this.studentName.compareTo(one.studentName);
}
// 用于(d)問題得到成績
public int getGrade() {
return grade;
}
// 用于(d)問題得到學(xué)生的姓名
public String getStudentName() {
return studentName;
}
}
// 主類task3
public class task3 {
public static void main(String[] args) {
// 數(shù)據(jù)文件名
String fileName = "data.txt";
// 從文件讀取數(shù)據(jù),并存到集合對象studentList中
List<Student> students = readStudentToList(fileName);
// 按學(xué)生名字升序排列
Collections.sort(students);
// 打印排序后的學(xué)生信息
// for (Student student : students) {
// System.out.println(student);
//}
String fileName1 = "output.txt";
//檢查文件是否存在,如果不存在則創(chuàng)建
File file = new File(fileName1);
try {
if(!file.exists())
{
file.createNewFile();
System.out.println(fileName1+"已創(chuàng)建。");
}
}
catch (IOException e) {
e.printStackTrace();
}
// 序列化數(shù)據(jù)到output.txt
serialize(students,fileName1);
// 反序列化數(shù)據(jù)
List<Student> students1 = deserialize(fileName1);
// 輸出成績在92分以上的學(xué)生
show92up(students1);
//刪除文件,以便能夠多次運行
if (file.delete()) {
System.out.println(fileName1+"已刪除。" );
} else {
System.out.println(fileName1+"無法刪除");
}
}
// 從文件中讀取數(shù)據(jù),返回一個包含Student對象的List
private static List<Student> readStudentToList(String fileName){
// 用于返回List的臨時變量
List<Student> tempList = new ArrayList<>();
try(BufferedReader reader = new BufferedReader(new FileReader(fileName))){
String lineString;
//逐行讀取文件內(nèi)容
while((lineString = reader.readLine())!=null) {
// 拆分獲取每個學(xué)生的具體信息
String[] strings = lineString.split(" ");
// 獲取后創(chuàng)建Student對象
Student temp = new Student(Integer.parseInt(strings[0]),
strings[1], strings[2], Integer.parseInt(strings[3]));
// 將創(chuàng)建后的對象加入List中
tempList.add(temp);
}
}
catch(IOException e) {
e.printStackTrace();
}
// 返回包含Student對象的List
return tempList;
}
// 序列化集合中的數(shù)據(jù)到output.txt中
private static void serialize(List<Student> temp,String fn) {
// 在這里是 ObjectOutputStream)會在代碼塊結(jié)束時自動關(guān)閉,不需要顯式調(diào)用 close() 方法來釋放資源
try(ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fn))){
oos.writeObject(temp);
}catch (IOException e) {
e.printStackTrace();
}
}
// 將output.txt中的數(shù)據(jù)反序列化
private static List<Student>deserialize(String fn){
// 用于返回包含Student的List
List<Student> tempList = new ArrayList<>();
// 將反序列化后的對象轉(zhuǎn)換為 List<Student>
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(fn))) {
Object object = ois.readObject();
//判斷 object 是否是 List 類型
if(object instanceof List<?>) {
//將 object 強制轉(zhuǎn)換為 List 類型,可以逐個遍歷其中的元素
List<?> unkown = (List<?>) object;
// 遍歷List中是否為Student類
for(Object i : unkown) {
// 如果是就加入List(強制轉(zhuǎn)換以保證一定為Student類)
if(i instanceof Student) {
tempList.add((Student)i);
}else {
System.err.println("列表里有不是學(xué)生的元素!");
}
}
}else {
System.err.println("這不是我們想要的列表!");
}
}catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
// 返回包含學(xué)生的List
return tempList;
}
// 按照規(guī)定輸出成績在92分以上的學(xué)生信息
private static void show92up(List<Student>temp){
temp.stream()// 將集合轉(zhuǎn)換為流
// 過濾操作,保留成績大于92的學(xué)生
.filter(t->t.getGrade()>92)
// 排序操作,首先按照學(xué)生成績降序排序,然后按照學(xué)生名字的字母順序升序排序
// 使用 Comparator.comparing 方法,通過方法引用指定按照哪個屬性進行比較
.sorted(Comparator.comparing(Student::getGrade).reversed().
thenComparing(Student::getStudentName))
// 遍歷操作,將每個學(xué)生信息打印到控制臺
.forEach(System.out::println);
}
}
到了這里,關(guān)于Java程序設(shè)計:選實驗6 輸入輸出應(yīng)用的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!