实验5 流(4学时)
**二、实验内容
1.编写程序,要求:用户在键盘每输入一行文本,程序将这段文本显示在控制台中。当用户输入的一行文本是“exit”(不区分大小写)时,程序将用户所有输入的文本都写入到文件log.txt中,并退出。(要求:控制台输入通过流封装System.in获取,不要使用Scanner)
public class Main{
public static void main(String[] args) throws IOException {
BufferedReader scanner = null; //读取流
BufferedWriter bw = null; //写出流
try{
scanner = new BufferedReader(new InputStreamReader(System.in));
bw = new BufferedWriter(new FileWriter("C:\\Users\\fhawk\\IdeaProjects\\Test1\\src\\PTA\\log.txt"));
while(true)
{
String s = scanner.readLine();
if(s.equals("exit"))
{
break;
}
bw.write(s); //将键盘输入写入文件中
bw.newLine(); //格式控制
System.out.println(s);
}
bw.flush();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}finally {
scanner.close();
}
}
}
设计学生类Student,属性:学号(整型);姓名(字符串),选修课程(名称)及课程成绩(整型)。编写一个控制台程序,能够实现Student信息的保存、读取。具体要求:(1)提供Student信息的保存功能:通过控制台输入若干个学生的学号、姓名以及每个学生所修课程的课程名和成绩,将其信息保存到data.dat中;(2)数据读取显示:能够从data.dat文件中读取学生及其课程成绩并显示于控制台。**
package PTA;
import java.io.*;
import java.util.*;
import java.util.Scanner;
public class Main {
public static void main(String args[]) throws IOException, ClassNotFoundException {
Scanner sc = new Scanner(System.in);
Save();
Read();
}
public static void Read() throws IOException, ClassNotFoundException {
//定义对象流来接受学生对象
ObjectInputStream oi = null;
oi = new ObjectInputStream(new FileInputStream("C:\\Users\\fhawk\\IdeaProjects\\Test1\\src\\PTA\\data.dat"));
//定义一个链表
LinkedList<Student> linkedList = new LinkedList<>();
while(true)
{
//链表存入学生对象(通过流读取)
Student stu = (Student) oi.readObject();
if(stu==null) break;
linkedList.add(stu);
}
Iterator<Student> iterator = linkedList.iterator();
while(iterator.hasNext())
{
System.out.println(iterator.next());
}
}
public static void Save() throws IOException {
Scanner sc = new Scanner(System.in);
//保存功能 对象输出流,写出到文件
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("C:\\Users\\fhawk\\IdeaProjects\\Test1\\src\\PTA\\data.dat"));
while(true)
{
System.out.println("是否继续录入数据?Y/N");
String msg = sc.nextLine();
if(msg.equals("Y")||msg.equals("y"))
{
Student student = new Student();
System.out.println("请输入学号");
String no = sc.nextLine();
System.out.println("请输入名字");
String name = sc.nextLine();
student.setNo(Integer.parseInt(no));
student.setName(name);
//System.out.println(student.getName()+"hihihi"+student.getNo());
//将对象写出到流中
os.writeObject(student);
os.flush();
}else
{
os.writeObject(null);
break;
}
}
}
}
class Student implements Serializable{
int no;
String name;
public Student() {
}
public Student(int no, String name) {
this.no = no;
this.name = name;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "学号:"+no+" 名字:"+name;
}
}