输入与输出实验

(一)查看并运行下列程序并回答问题。
package case1;

import java.io.*;

public class IOExample {
    public static void main(String[] args) throws IOException {

        // 一行一行读入数据
        BufferedReader in = new BufferedReader(new FileReader("IOExample.java"));
        String str;
        String str2 = new String();
        while ((str = in.readLine()) != null) {
            str2 = str2 + str + "\n";
        }
        in.close();

        // 从内存输入
        StringReader reader = new StringReader(str2);
        int outChar;
        while ((outChar = reader.read()) != -1) {
            System.out.print((char) outChar);
        }

        // 从标准输入读取数据
        BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("输入一行数据:");
        System.out.println("您输入的是:" + stdIn.readLine());

        // 输出到文件
        try {
            BufferedReader sIn = new BufferedReader(new StringReader(str2));
            PrintWriter fileOut = new PrintWriter(new BufferedWriter(new FileWriter("IOExample.out")));
            int lineNo = 1;
            while ((str = sIn.readLine()) != null) {
                fileOut.println((lineNo++) + ":" + str);
            }
            fileOut.close();
        } catch (EOFException ex) {
            System.err.println("到达流末尾");
        }
    }
}

从文件按行缓冲读取数据的程序时哪一段?

        BufferedReader in = new BufferedReader(new FileReader("IOExample.java"));
        String str;
        String str2 = new String();
        while ((str = in.readLine()) != null) {
            str2 = str2 + str + "\n";
        }
        in.close();

从内存输入的程序时哪一段?

 StringReader reader = new StringReader(str2);
        int outChar;
        while ((outChar = reader.read()) != -1) {
            System.out.print((char) outChar);
        }

从标准输入读取数据是哪一段?

BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("输入一行数据:");
        System.out.println("您输入的是:" + stdIn.readLine());

输出到文件的程序是哪一段?

try {
            BufferedReader sIn = new BufferedReader(new StringReader(str2));
            PrintWriter fileOut = new PrintWriter(new BufferedWriter(new FileWriter("IOExample.out")));
            int lineNo = 1;
            while ((str = sIn.readLine()) != null) {
                fileOut.println((lineNo++) + ":" + str);
            }
            fileOut.close();
        } catch (EOFException ex) {
            System.err.println("到达流末尾");
        }
(二)查看下列程序并运行并回答问题。
package case2;

import java.io.*;

public class FileInputOutputExam {
    public static void main(String[] args) {
        if (args.length != 2) {
            System.out.println("请指定2个参数,源文件和目标文件名称!");
            System.exit(-1);
        }
        FileInputStream in = null;
        FileOutputStream out = null;
        try {
            in = new FileInputStream(args[0]);
        } catch (FileNotFoundException ex) {
            System.out.println("无法打开源文件或该文件不存在!");
            System.exit(-2);
        }
        try {
            out = new FileOutputStream(args[1]);
        } catch (FileNotFoundException ex) {
            System.out.println("无法打开目标文件或该文件无法创建!");
            System.exit(-3);
        }
        int c;
        try {
            while ((c = in.read()) != -1) {
                out.write(c);
            }
            in.close();
            out.close();
        } catch (IOException ioEx) {
            ioEx.printStackTrace();
        }
    }
}

分析此程序完成了什么功能?
程序实现了文件的复制;
程序每一部分的作用是什么?

package case2;

import java.io.*;

public class FileInputOutputExam {
    // 选择所要操作的源文件与其目标文件名
    public static void main(String[] args) {
        if (args.length != 2) {
            System.out.println("请指定2个参数,源文件和目标文件名称!");
            System.exit(-1);
        }
        FileInputStream in = null;
        FileOutputStream out = null;
        // 打开所选择的源文件
        try {
            in = new FileInputStream(args[0]);
        } catch (FileNotFoundException ex) {
            System.out.println("无法打开源文件或该文件不存在!");
            System.exit(-2);
        }
        try {
            out = new FileOutputStream(args[1]);
        } catch (FileNotFoundException ex) {
            System.out.println("无法打开目标文件或该文件无法创建!");
            System.exit(-3);
        }
        int c;
        // 复制该文件
        try {
            while ((c = in.read()) != -1) {
                out.write(c);
            }
            in.close();
            out.close();
        } catch (IOException ioEx) {
            ioEx.printStackTrace();
        }
    }
}
(三)观察并运行下列两段程序,理解数据输入/输出流的使用。

说明:先执行DataOutputExample.class,再执行DataInputExample.class

package case3;

import java.io.*;

public class DataOutputExample {
    public static void main(String args[]) {
        try {
            FileOutputStream fout = new FileOutputStream(args[0]);
            DataOutputStream dataOut = new DataOutputStream(fout);
            double data;
            for (int i = 0; i < 10; i++) {
                data = Math.random();
                System.out.println(data);
                dataOut.writeDouble(data);
            }
            dataOut.close();
            fout.close();
        } catch (IOException e) {
            System.err.print(e);
        }
    }
}
package case3;

import java.io.*;

public class DataInputExample {
    public static void main(String args[]) {
        try {
            FileInputStream fin = new FileInputStream(args[0]);
            DataInputStream dataIn = new DataInputStream(fin);
            while (fin.available() > 0) {
                System.out.println(dataIn.readDouble());
            }
            dataIn.close();
            fin.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
(四)补充并运行下列程序,理解File类对文件及目录操作。
import java.io.*;
import java.text.SimpleDateFormat;

public class FileExample {
		
	public void fileInfo(File f) throws IOException{
		System.out.println("文件名:"+          );
		System.out.println("文件是否可被读取:"+(        ?"是":"否"));
		System.out.println("文件是否可被修改:"+(         ?"是":"否"));
		System.out.println("文件的绝对路径:"+              );
		System.out.println("文件长度:"+             +"字节");
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        System.out.println("文件最后被修改时间:"+sdf.format(f.lastModified()));
	}
	
	public void dirInfo(File f) throws IOException{
		System.out.println("目录名:"+            );
		System.out.println("该目录下包含如下子目录和文件:");
		//补充代码段,输出子目录和文件
	}
	
	public static void main(String [] args) throws IOException {
		if(args.length <= 0){
			System.out.println("请通过命令行参数指定文件或目录名!");
			System.exit(0);
		}else {
			File file = new File(args[0]);
			if(file.isFile()){
				new FileExample().fileInfo(file);
			} else if(file.isDirectory()){
				new FileExample().dirInfo(file);
			} else {
				file.createNewFile();
			}
		}		
	}
}
package case4;

import java.io.*;
import java.text.SimpleDateFormat;

public class FileExample {

    public void fileInfo(File f) throws IOException {
        System.out.println("文件名:" + f.getName());
        System.out.println("文件是否可被读取:" + (f.canRead() ? "是" : "否"));
        System.out.println("文件是否可被修改:" + (f.canWrite() ? "是" : "否"));
        System.out.println("文件的绝对路径:" + f.getAbsolutePath());
        System.out.println("文件长度:" + f.length() + "字节");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        System.out.println("文件最后被修改时间:" + sdf.format(f.lastModified()));
    }

    public void dirInfo(File f) throws IOException {
        System.out.println("目录名:" + f.getName());
        System.out.println("该目录下包含如下子目录和文件:");
        // 补充代码段,输出子目录和文件
        String[] dirArr = f.list();
        for (int i = 0; i < dirArr.length; i++) {
            System.out.println("" + (i + 1) + ":" + dirArr[i]);
        }

    }

    public static void main(String[] args) throws IOException {
        if (args.length <= 0) {
            System.out.println("请通过命令行参数指定文件或目录名!");
            System.exit(0);
        } else {
            File file = new File(args[0]);
            if (file.isFile()) {
                new FileExample().fileInfo(file);
            } else if (file.isDirectory()) {
                new FileExample().dirInfo(file);
            } else {
                file.createNewFile();
            }
        }
    }
}
(五)观察并运行下列程序,理解使用对象流对文件进行读写的过程。
package case5;

import java.io.*;

/**
 * 员工类,可序列化
 */
class Employee implements Serializable {
    int employeeId_;
    String name_;
    int age_;
    String department_;

    public Employee(int employeeId, String name, int age, String department) {
        this.employeeId_ = employeeId;
        this.name_ = name;
        this.age_ = age;
        this.department_ = department;
    }

    public void showEmployeeInfo() {
        System.out.println("employeeId:" + employeeId_);
        System.out.println("name:" + name_);
        System.out.println("age:" + age_);
        System.out.println("department:" + department_);
        System.out.println("-----信息输出完毕-----");
    }
}

/**
 * 对可序列化对象操作
 */
public class ObjectSerializeExam {
    public static void main(String[] args) {
        // 建立两个员工对象
        Employee e1 = new Employee(100101, "Tom", 41, "HR");
        Employee e2 = new Employee(100102, "Jerry", 22, "Sales");
        try {
            // 建立对象输出流将对象写出到文件employee.data
            FileOutputStream fos = new FileOutputStream("employee.data");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(e1);
            oos.writeObject(e2);
            oos.close();
            // 建立对象输入流将对象从文件employee.data中还原
            FileInputStream fis = new FileInputStream("employee.data");
            ObjectInputStream ois = new ObjectInputStream(fis);
            e1 = (Employee) ois.readObject();
            e2 = (Employee) ois.readObject();
            ois.close();
            // 显示对象信息
            e1.showEmployeeInfo();
            e2.showEmployeeInfo();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
(五)编写一个学生类Student和一个文件随机存取类RandomAccessFileExam。Student类中有名字和成绩两个属性,以及构造方法、get/set方法和指定每个属性固定写入34字节的方法。在RandomAccessFileExam类中生成四个学生记录,保存到随机存取文件中,并能够随机读取出任何一条学生记录。
package case6;

import java.io.File;
import java.io.RandomAccessFile;
import java.io.*;
import java.util.Scanner;

class Student {
    private String name;
    private int score;

    public Student() {
        setName("");
    }

    public Student(String name, int score) {
        setName(name);
        this.score = score;
    }

    public String getName() {
        return name;
    }

    public int getScore() {
        return score;
    }

    public void setScore(int score) {
        this.score = score;
    }

    public void setName(String name) {
        StringBuilder builder = null;
        if (name != null) {
            builder = new StringBuilder(name);
        } else {
            builder = new StringBuilder(15);
        }
        builder.setLength(15);
        this.name = builder.toString();
    }

    public static int size() {
        return 34;
    }
}

public class RandomAccessFileExam {
    public RandomAccessFileExam(File file, String string) {
    }

    public static void main(String[] args) {
        Student[] students = {
                new Student("A", 100),
                new Student("B", 90),
                new Student("C", 80),
                new Student("D", 70),
                new Student("E", 60)
        };
        try {
            File file = new File(args[0]);
            RandomAccessFileExam randomAccessFileExam = new RandomAccessFileExam(file, "rw");
            for (int i = 0; i < students.length; i++) {
                randomAccessFileExam.writeChars(students[i].getName());
                randomAccessFileExam.writeInt(students[i].getScore());
            }
            Scanner scanner = new Scanner(System.in);
            System.out.println("读取第几条学生的记录");

            int num = scanner.nextInt();
            RandomAccessFile.seek((num - 1) * Students.length());
            Student student = new Student();
            student.setName(readName(randomAccessFile));
            student.setScore(randomAccessFile.readInt());
            System.out.println("姓名" + student.getName());
            System.out.println("分数" + student.getScore());
            randomAccessFile.close();
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("请指定文件名称");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void writeInt(int score) {
    }

    private void writeChars(String name) {
    }

    private static String readName(RandomAccessFile randomAccessFile)
        throws IOException {
        char[] name = new char[15];
        for (int i = 0; i < name.length; i++) {
            name[i] = randomAccessFile.readChar();
        }
        return new String(name).replace('\0', ' ');
    }
}
(六)字节流和字符流有什么区别?

①组成不同:字节流是由字节组成的,字符流是由字符组成的;
②处理不同:字符流的处理主要用于处理二进制数据,而字符流的处理是按虚拟机的encode来处理,也就是要进行字符集的转化。

(七)常用输入类有哪些?

FileInputStream,ByteArrayInputStream,PipedInputStream,BufferdInputStream,DataInputStream,FileReader,CharArrayReader,StringReader,PipedReader,BufferedReader.

(八)常用输出类有哪些?

FileOutputStream,ByteArrayOutputStream,PiipedOutputStream,BufferdOutputStream,DataOutputStream,DataOutputStream,PrintStream,FIleWriter,CharArrayWriter,StringWriter,PipedWriter,BufferedWriter,PrintWriter

(九)对文件和目录的操作主要有哪两个类?简单描述一下。

①File类:所代表的不仅限于文件,它既可以代表一个文件的名称,又可以代表某一目录下面的一组文件的名称。File类提供了一组丰富的方法来操作文件和目录,例如访问文件的属性,更改文件名称,创建和删除文件或目录,列出目录下包含的文件等。
②RandomAccessFile类:有时会用文件来保存一些记录集,再次访问这些记录时并不是将文件从头到尾,而是一条记录一条记录地读取或修改。

(十)什么叫对象的序列化操作?

将实现了序列化接口的对象转化成字节序列进行保存或传输,以后还能够根据该字节序列将对象完全还原。

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值