IO题目
阅读原文时间:2023年07月09日阅读:4

8-1 写入日志文件 (0 分)

编写程序,要求:用户在键盘每输入一行文本,程序将这段文本显示在控制台中。当用户输入的一行文本是“exit”(不区分大小写)时,程序将用户所有输入的文本都写入到文件log.txt中,并退出。(要求:控制台输入通过流封装System.in获取,不要使用Scanner)

import java.io.*;

public class Main
{
public static void main(String[] args)
{
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new InputStreamReader(System.in));
bw = new BufferedWriter(new FileWriter(new File("log.txt")));
String s;
while(!(s = br.readLine()).equalsIgnoreCase("exit"))
{
System.out.print(s);
bw.write(s);
bw.newLine();
}
}catch(IOException e) {
e.printStackTrace();
}

    finally {  
        try {  
            if(br != null)  
            {  
                br.close();  
            }  
            if(bw != null)  
            {  
                bw.close();  
            }  
        }catch(IOException e) {  
            e.printStackTrace();  
        }  
    }  
}  

}

8-2 文件和目录输出 (20 分)

查看File类的API文档,使用该类实现一个类FileList,它提供两个静态方法:1)readContentsInDirectory(String path):能够将输入参数path所指定的本地磁盘路径下的所有目录和文件的名称打印出来;2)readContentsInDirectoryRecursive(String path):能够将输入参数path所指定的本地磁盘路径下的所有目录(包含所有子孙目录)和文件的名称以层次化结构打印出来。程序的输出如下所示。

import java.io.*;
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
String path = s.nextLine();
File f = new File(path);
int level = 0;
FileList fl = new FileList();
fl.readContentsInDirectory(f);
System.out.println("------------------");
fl.readContentsInDirectoryRecursive(f, level);
s.close();
}
}
class FileList
{
public void readContentsInDirectory(File path)
{
if(!path.exists())
{
System.out.println("路径"+path.getPath()+"不存在");
return ;
}
else
{
File[] f = path.listFiles();
for(int i = 0 ; i < f.length ; i++)
{
if(f[i].isFile())
{
System.out.println("[文件]"+f[i].getName());
}
else
{
System.out.println("[目录]"+f[i].getName());
}
}
}
}
public void readContentsInDirectoryRecursive(File path,int level)
{
if(!path.exists())
{
System.out.println("路径"+path.getPath()+"不存在");
return ;
}
else
{
File[] f = path.listFiles();
for(int i = 0 ; i < f.length ; i++)
{
for(int j = 0; j < level ; j++)
{
System.out.print("-");
}
if(f[i].isFile())
{
System.out.println("[文件]"+f[i].getName());
}
else
{
System.out.println("[目录]"+f[i].getName());
readContentsInDirectoryRecursive(f[i],level+2);
}
}
}
}
}

8-3 菜单文件处理 (20 分)

假设某个餐馆平时使用:1)文本文件(orders.txt)记录顾客的点菜信息,每桌顾客的点菜记录占一行。每行顾客点菜信息的记录格式是“菜名:数量,菜名:数量,…菜名:数量”。例如:“烤鸭:1,土豆丝:2,烤鱼:1”。2)文本文件(dishes.txt)记录每种菜的具体价格,每种菜及其价格占一行,记录格式为“菜名:价格“。例如:“烤鸭:169”。编写一个程序,能够计算出orders.txt中所有顾客消费的总价格。(注意,请使用文本读写流,及缓冲流来处理文件)

import java.util.*;
import java.io.*;
public class Main
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
BufferedReader br1 = null;
BufferedReader br2 = null;
List order = new ArrayList<>();
Map dish = new HashMap<>();
try {
File f1 = new File("order.txt");
f1.createNewFile();
File f2 = new File("dishes.txt");
f2.createNewFile();
br1 = new BufferedReader(new FileReader("order.txt"));
br2 = new BufferedReader(new FileReader("dishes.txt"));
String S1 ;
while((S1 = br1.readLine()) != null)
{
String[] s1 = S1.split(",");
for(int i = 0 ; i < s1.length ; i++)
{
order.add(new Order(s1[0],Integer.parseInt(s1[1])));
}
}
String S2;
while((S2 = br2.readLine()) != null)
{
String[] s2 = S2.split(":");
dish.put(s2[0], new Dish(s2[0],Double.parseDouble(s2[1])));
}
double sum = 0;
for(int i = 0 ; i < order.size() ; i++)
{
sum += order.get(i).num * dish.get(i).price;
}
System.out.println(sum);
}catch(Exception e) {
e.printStackTrace();
}
finally {
try {
if(br1 != null)
{
br1.close();
}
if(br2 != null)
{
br2.close();
}
}catch(Exception e) {
e.printStackTrace();
}
}
s.close();
}
}
class Order
{
public String name;
public int num;
public Order(String name, int num)
{
this.name = name;
this.num = num;
}
}
class Dish
{
public String name;
public double price;
public Dish(String name, double price)
{
this.name = name;
this.price = price;
}
}

8-4 成绩文件处理 (20 分)

设计学生类Student,属性:学号(整型);姓名(字符串),选修课程(名称)及课程成绩(整型)。编写一个控制台程序,能够实现Student信息的保存、读取。具体要求:(1)提供Student信息的保存功能:通过控制台输入若干个学生的学号、姓名以及每个学生所修课程的课程名和成绩,将其信息保存到data.dat中;(2)数据读取显示:能够从data.dat文件中读取学生及其课程成绩并显示于控制台。(要求,学号和课程成绩按照整数形式(而非字符串形式)存储)

import java.io.*;
import java.util.*;

public class Test4 {

public static void main(String\[\] args) {  
    Scanner sc = new Scanner(System.in);  
    String l = null;  
    DataInputStream dis = null;  
    DataOutputStream dos = null;  
    try {  
        dos = new DataOutputStream(new FileOutputStream("data.dat"));  
        while(!(l=sc.nextLine()).equals("exit")) {  
            String\[\] ss = l.split(" ");  
            Student s = new Student(Integer.parseInt(ss\[0\])  
                    ,ss\[1\],ss\[2\],Integer.parseInt(ss\[3\]));

            byte\[\] bs = s.getNameBytes();  
            byte\[\] cs = s.getCourseBytes();

            dos.writeInt(s.no);  
            dos.writeInt(bs.length);  
            dos.write(bs);  
            dos.writeInt(cs.length);  
            dos.write(cs);  
            dos.writeInt(s.score);  
        }  
    } catch (Exception e) {  
        e.printStackTrace();  
    } finally {  
        try {  
        dos.close();  
        }catch (IOException e) {  
            e.printStackTrace();  
        }  
    }

    try {  
        File f = new File("data.dat");  
        int size = (int) f.length();  
        int records = size/(4+4+(96+240)/8);  
        dis = new DataInputStream(new FileInputStream("data.dat"));

        while (true) {//for (int i=0;i<records;i++) {  
            int no = dis.readInt();  
            int bsize = dis.readInt();  
            byte\[\] bs = new byte\[bsize\];  
            dis.read(bs);  
            String name = new String(bs);  
            int wsize = dis.readInt();  
            byte\[\] ws = new byte\[wsize\];  
            dis.read(ws);  
            String course = new String(ws);  
            int score = dis.readInt();  
            System.out.println(no+" "+name+" "+course+" "+score);  
        }  
    } catch (EOFException e) {  
        System.out.println("end of file");  
    } catch (IOException e){  
        e.printStackTrace();  
    }finally {  
        try {  
        dis.close();  
        }catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  
}

}

class Student {
int no;
String name;
String course;
int score;

public byte\[\] getNameBytes() {  
    byte\[\] src = name.getBytes();  
    return src;  
}

public byte\[\] getCourseBytes(){  
    byte\[\] src = course.getBytes();  
    return src;  
}

public Student(int no, String name, String course, int score) {  
    super();  
    this.no = no;  
    this.name = name;  
    this.course = course;  
    this.score = score;  
}

}

8-5 图书馆持久化 (20 分)

构造图书类,包含名称(字符串)、作者(字符串)、出版社(字符串)、版本号(整数)、价格(浮点数),构造图书馆类,其中包含若干图书,用容器存储图书对象,然后定义方法void addBook(Book b)添加图书对象,定义方法void persist(),将所有图书存至本地文件books.dat里,定义方法Book[] restore() 从文件books,dat中读取所有图书,并返回图书列表数组。 main函数中构造图书馆类对象,向其中添加3个图书对象,测试其persist和restore方法。(注意,请使用对象序列化方法实现)

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class Test5 {
/*构造图书类,包含名称(字符串)、作者(字符串)、出版社(字符串)、版本号(整数)、价格(浮点数),
* 构造图书馆类,其中包含若干图书,用容器存储图书对象,
* 然后定义方法void addBook(Book b)添加图书对象,
* 定义方法void persist(),将所有图书存至本地文件books.dat里,
* 定义方法Book[] restore() 从文件books,dat中读取所有图书,并返回图书列表数组。
* main函数中构造图书馆类对象,向其中添加3个图书对象,测试其persist和restore方法。
* (注意,请使用对象序列化方法实现)
*/

public static void main(String\[\] args) {  
    ObjectOutputStream oos = null;  
    Book\[\] bs = {  
            new Book ("Java","张峰", "清华大学出版社",2, 23.5),  
            new Book ("C++","刘冰", "清华大学出版社",2, 18),  
            new Book ("C","王莉", "清华大学出版社",2, 35)  
    };  
    Library l = new Library();  
    for (Book b : bs) {  
        l.addBook(b);  
    }  
    l.persist();  
    Book\[\] bs2 = l.restore();  
    for (Book b : bs) {  
        System.out.println(b);  
    }  
}

}

class Book implements Serializable{
String name;
String author;
String press;
int edition;
double price;

public Book(String name, String author, String press, int edition, double price) {  
    super();  
    this.name = name;  
    this.author = author;  
    this.press = press;  
    this.edition = edition;  
    this.price = price;  
}

@Override  
public String toString() {  
    return "Book \[name=" + name + ", author=" + author + ", press=" + press + ", edition=" + edition + ", price="  
            + price + "\]";  
}  

}

class Library
{
List bs = new ArrayList();

public void addBook(Book b)  
{  
    bs.add(b);  
}

public void persist ()  
{  
    ObjectOutputStream oos = null;  
    try {  
        oos = new ObjectOutputStream(  
                new FileOutputStream("books.dat"));  
            // 将per对象写入输出流  
        for(Book b :bs)  
        oos.writeObject(b);  
    }  
    catch (IOException ex)  
    {  
        ex.printStackTrace();  
    } finally {  
        try {  
            if (oos!=null)  
                oos.close();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
}

public Book\[\] restore()  
{  
    ObjectInputStream ois = null;  
    bs = new ArrayList<Book>();  
    try {  
        ois = new ObjectInputStream(  
            new FileInputStream("books.dat"));  
        //从输入流中读取一个Java对象,并将其强制类型转换为Person类  
        while (true)  
        {  
            Book b = (Book)ois.readObject();  
            bs.add(b);  
        }  
    }catch (EOFException e){  
      System.out.println("end of file");  
    }catch (Exception e){  
        e.printStackTrace();  
    }finally {  
        try {  
            if (ois!=null)  
                ois.close();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
    Book\[\] ba = new Book\[bs.size()\];  
    bs.toArray(ba);  
    return ba;  
}

}

8-6 按行读文件 (20 分)

使用java的输入/输出流技术将一个文本文件的内容按行读出,每读出一行就顺序添加行号,并写入到另一个文件中。

import java.io.*;
public class Main
{
public static void main(String[] args)
{
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader("in.txt"));
bw = new BufferedWriter(new FileWriter("out.txt"));
String s;
for(int i = 0 ; (s = br.readLine())!=null ; i++)
{
bw.write(i+" , "+s);
bw.newLine();
}
}catch(Exception e) {
e.printStackTrace();
}
finally {
try {
if(br != null)
{
br.close();
}
if(bw != null)
{
bw.close();
}
}catch(Exception e) {
e.printStackTrace();
}
}
}
}

8-7 读写文件--程序设计 (20 分)

编写一个程序实现如下功能,文件fin.txt是无行结构(无换行符)的汉语文件,从fin中读取字符,写入文件fou.txt中,每40个字符一行(最后一行可能少于40个字) 请将程序代码贴到答案区内

import java.io.*;
public class Main
{
public static void main(String[] args)
{
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader("fin.txt"));
bw = new BufferedWriter(new FileWriter("out.txt"));
char[] c = new char[40];
int len = 40;
while((br.read(c, 0, len) )!= -1)
{
bw.write(c, 0, len);
bw.newLine();
}
}catch(Exception e) {
e.printStackTrace();
}
finally {
try {
if(br != null)
{
br.close();
}
if(bw != null)
{
bw.close();
}
}catch(Exception e) {
e.printStackTrace();
}
}
}
}