IO流作业

一、填空题
1.IO的含义是 ,data source的含义是 。
2.Java IO流可以分为 和处理流两大类,其中前者处于IO操作的第一线,所有操作必须通过他们进行。
3.输入流的唯一目的是提供通往数据的通道,程序可以通过这个通道读取数据,
方法给程序提供了一个从输入流中读取数据的基本方法。
4.read方法从输入流中顺序读取源中的单个字节数据,该方法返回字节值(0-255之间的一个整数),如果到达源的末尾,该方法返回 。
5.Java系统的标准输入对象是System.in,标准输出对象有两个,分别是标准输出System.out和标准错误输出____________________。
6.Java IO体系中,____________是字节输入流,不仅提供了存取所有Java基础类型数据(如:int,double 等)和String的方法,也提供了提供存取对象的方法。
7.Java IO体系中,是字节输出流,提供了可以存取所有Java基础类型数据(如:int,double 等)和String的方法,但没有提供存取对象的方法。
8.是指将Java对象转换成字节序列,从而可以保存到磁盘上,也可以在网络上传输,使得不同的计算机可以共享对象。
9.transient的作用是。

二、选择题

使用Java IO流实现对文本文件的读写过程中,需要处理下列( )异常。(选择一项)

A ClassNotFoundException
B. IOException
C. SQLException
D. RemoteException

在Java的IO操作中,( )方法可以用来刷新流的缓冲。(选择两项)

A void release()
B. void close()
C. void remove()
D. void flush()

在Java中,下列关于读写文件的描述错误的是( )。(选择一项)

A Reader类的read()方法用来从源中读取一个字符的数据
B. Reader类的read(int n )方法用来从源中读取一个字符的数据
C. Writer类的write(int n)方法用来向输出流写入单个字符
D. Writer类的write(String str)方法用来向输出流写入一个字符串

阅读下列文件定入的Java代码,共有( )处错误。(选择一项)
import java.io.*;
public class TestIO {undefined
public static void main(String []args){undefined
String str =“文件写入练习”;
FileWriter fw = null; //1
try{undefined
fw = new FileWriter(“c:\mytext.txt”); //2
fw.writerToEnd(str); //3
}catch(IOException e){ //4
e.printStackTrace();
}finally{undefined
//此处省略关闭流
}
}
}

A 0
B. 1
C. 2
D. 3

分析如下Java代码,有标注的四行代码中,有错误的是第( )处。(选择一项)
import java.io.FileWriter;
import java.io.IOException;
public class Test {undefined
public static void main(String[ ] args) {undefined
String str = “Hello World”;
FileWriter fw = null;
try {undefined
fw = new FileWriter(“c:\hello.txt”); // 1
fw.write(str); // 2
} catch (IOException e) {undefined
e.printStackTrace(); // 3
} finally {undefined
fw.close(); // 4
}
}
}

A 1
B. 2
C. 3
D. 4

以下选项中关于如下代码的说法正确的是( )。(选择二项)
public class TestBuffered {undefined
public static void main(String[] args) throws IOException {undefined
BufferedReader br =
new BufferedReader(new FileReader(“d:/glls1.txt”));
BufferedWriter bw =
new BufferedWriter(new FileWriter(“d:/glls2.txt”));
String str = br.readLine();
while(str !=null){undefined
bw.write(str);
bw.newLine();
str = br.readLine();
}
br.close();
bw.close();
}
}

A. 该类使用字符流实现了文件复制,将d:/glls1.txt复制为d:/glls2.txt
B. FileReader和FileWriter是处理流,直接从文件读写数据
C. BufferedReader和BufferedWriter是节点流,提供缓冲区功能,提高读写效率
D. readLine()可以读取一行数据,返回值是字符串类型,简化了操作

InputStreamReader是转换流,可以将字节流转换成字符流,是字符流与字节流之间的桥梁。它的实现使用的设计模式是( )。(选择一项)

A. 工厂模式
B. 装饰模式
C. 适配器模式
D. 代理模式

三、判断题
1.假设文件”a.txt”的长度为100字节,那么当正常运行语句”OutputStream f=new FileOutputStream(new File(“a.txt”));”之后,文件”a.txt”的长度变为0字节。( )
2.ByteArrayInutStream和ByteArrayOutputStream对内存中的字节数组进行读写操作,属于字节流,属于处理流而不是节点流。 ( )
3.实现Serializable接口的可以被序列化和反序列化。该接口中没有定义抽象方法,也没有定义常量。( )
4.序列化是指将字节序列转换成Java对象,只有实现了Serializable接口的类的对象才可以被序列化。( )
5.流对象使用完后,一般要调用close方法关闭,释放资源。 ( )

四、简答题
1.输入流和输出流的联系和区别,字符流和字节流的联系和区别
2.节点流和处理流的联系和区别。
3.列举常用的字节输入流和字节输出流并说明其特点,至少5对。
4.说明缓冲流的优点和原理。
5.序列化的定义、实现和注意事项。反序列化指的是什么?
6.PrintStream打印流经常用于什么情况? System.out 是不是打印流?
7.word文档能使用字符流操作吗?为什么?

五、编码题
1.实现字符串和字节数组之间的相互转换。必如将字符串“xxxxxglls”转换为字节数组,并将字节数组再转换回字符串。
2.实现字节数组和任何基本类型和引用类型执行的相互转换
提示:使用ByteArrayInutStream和ByteArrayOutputStream。
3.分别使用文件流和缓冲流复制一个长度大于100MB的视频文件,并观察效率的差异。
4.复制文件夹d:/gllsjava下面所有文件和子文件夹内容到d:/gllsjava2。
提示:涉及单个文件复制、目录的创建、递归的使用
5.解释下面代码的含义:

File f = new File("d:/a.txt");
FileInputStream fis = new FileInputStream(f);
int m = 0;
while((m=fis.read())!=-1){
    char c = (char) m;
    System.out.print(c);
}
1
2
3
4
5
6
7
6.可选题
1.使用IO包中的类读取D盘上exam.txt文本文件的内容,每次读取一行内容,将每行作为一个输入放入ArrayList的泛型集合中并将集合中的内容使用加强for进行输出显示。

2.假设从入学开始所有书写的Java类代码都在d:/gllsjava文件夹下,包括多级子文件夹。使用IO流获取从入学开始,到目前为止已经写了多少行Java代码。
提示:其实就是获取d:/gllsjava文件夹及其子文件夹下的所有.java文件,使用readLine()读取其中每一行,每读取一行,行数加1。所有的文件读取完毕,得到总共已经写的Java代码行数。需要结合递归实现
3.由控制台按照固定格式输入学生信息,包括学号,姓名,年龄信息,当输入的内容为exit退出;将输入的学生信息分别封装到一个Student对象中,再将每个Student对象加入到一个集合中,要求集合中的元素按照年龄大小正序排序;最后遍历集合,将集合中学生信息写入到记事本,每个学生数据占单独一行。

IO流作业答案

一、填空题

1.输入输出,数据源
2.节点流
3.read
4.-1
5.System.err
6.ObjectInputStream
7.DataOutputStream
8.序列化
9.标识一个成员变量在序列化子系统中应被忽略

二、选择题

1.B
2.D
3.B
4.C
5.D
6.AD
7.C

三、判断题

1.√
2.×
3.√
4.×
5.√

四、简答题

答案略

五、编码题
1.实现字符串和字节数组之间的相互转换。比如将字符串“xxxxxglls”转换为字节数组,并将字节数组再转换回字符串。

public class TestConvert {
	public static void main(String[] args) throws IOException {
		//准备一个字符串
	String contents=" hello,xxxxxglls";
		System.out.println(contents);
		//String---byte [] 
		byte [] buf = contents.getBytes();	
		//byte[]----String
		String contents2 = new String(buf, 0, buf.length);
		System.out.println(contents2);		
	
	}
}

2.实现字节数组和任何基本类型和引用类型执行的相互转换
提示:使用ByteArrayInutStream和ByteArrayOutputStream。

public class TestByteArrayStream {
	public static void main(String[] args) throws IOException, 
									ClassNotFoundException {
		int num = 50;
		boolean flag = true;
		User user = new User("glls","glls");
		//使用数据包把数据封装起来
		//各种数据类型----->byte[]  ByteArrayOutputStream		
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream(baos);//包装流
		oos.writeInt(num);
		oos.writeBoolean(flag);
		oos.writeObject(user);		
		byte [] buf = baos.toByteArray();		
		baos.close();
		//byte[]----------->各种数据类型
		ByteArrayInputStream bais = new ByteArrayInputStream(buf);
		ObjectInputStream ois = new ObjectInputStream(bais);
		int num2 = ois.readInt();
		boolean flag2 = ois.readBoolean();
		User user2 = (User)ois.readObject();
		System.out.println(num2);
		System.out.println(flag2);
		System.out.println(user2);
		bais.close();

	}
}

3.分别使用文件流和缓冲流复制一个长度大于100MB的视频文件,并观察效率的差异。

public class TestCopy4 {
	public static void main(String[] args) throws IOException {
		//创建输入流和输出流
		InputStream fis = new FileInputStream(new File("d:/1.mp4"));
		OutputStream fos = new FileOutputStream("d:/2.mp4");
		//使用输入流和输出流复制文件
		byte [] buf = new byte[10];
		int len = fis.read(buf);
		while(len!=-1){
			//写
			fos.write(buf, 0, len);
			//读
			len = fis.read(buf);
			//System.out.println(len);
		}		
		//关闭输入流和输出流
		fis.close();
		fos.close();
	}
}
public class TestCopy {
	public static void main(String[] args) throws IOException {
		//创建输入流和输出流
		InputStream fis = new FileInputStream(new File("d:/1.mp4"));
		OutputStream fos = new FileOutputStream("d:/2.mp4");
		BufferedInputStream bis = new BufferedInputStream(fis);
		BufferedOutputStream bos = new BufferedOutputStream(fos);
		//使用输入流和输出流复制文件
		byte [] buf = new byte[10];
		int len = bis.read(buf);
		while(len!=-1){
			//写
			bos.write(buf, 0, len);
			//读
			len = bis.read(buf);
		}		
		//关闭输入流和输出流
		bis.close();
		bos.close();
	}
}

4.复制文件夹d:/gllsjava下面所有文件和子文件夹内容到d:/gllsjava2。
提示:涉及单个文件复制、目录的创建、递归的使用

public class CopyDir {
	/**
	 * 复制单个文件
	 * @param sourceFile 源文件
	 * @param targetFile 目标文件
	 * @throws IOException
	 */
    public static void copyFile(File sourceFile, File targetFile) throws IOException {
        BufferedInputStream inBuff = null;
        BufferedOutputStream outBuff = null;
        try {
            // 新建文件输入流
            inBuff = new BufferedInputStream(new FileInputStream(sourceFile));
            // 新建文件输出流
           outBuff = new BufferedOutputStream(new FileOutputStream(targetFile));
            // 缓冲数组
            byte[] b = new byte[1024 * 5];
            int len;
            while ((len = inBuff.read(b)) != -1) {
                outBuff.write(b, 0, len);
            }
            // 刷新此缓冲的输出流
            outBuff.flush();
        } finally {
            // 关闭流
            if (inBuff != null)
                inBuff.close();
            if (outBuff != null)
                outBuff.close();
        }
    }
    
    /**
     * 复制目录
     * @param sourceDir 源目录
     * @param targetDir 目标目录
     * @throws IOException
     */
public static void copyDirectiory(String sourceDir, String targetDir) 
throws IOException {
        // 检查源目录
    	File fSourceDir = new File(sourceDir);
    	if(!fSourceDir.exists() || !fSourceDir.isDirectory()){
    		System.out.println("源目录不存在");
    		return;
    	}    	
    	//检查目标目录,如不存在则创建
    	File fTargetDir = new File(targetDir);
    	if(!fTargetDir.exists()){
    		fTargetDir.mkdirs();
    	}    		
        // 遍历源目录下的文件或目录
        File[] file = fSourceDir.listFiles();
        for (int i = 0; i < file.length; i++) {
            if (file[i].isFile()) {
                // 源文件
                File sourceFile = file[i];
                // 目标文件
                File targetFile = new File(fTargetDir, file[i].getName());
                copyFile(sourceFile, targetFile);
            }            
            //递归复制子目录
            if (file[i].isDirectory()) {
                // 准备复制的源文件夹
                String subSourceDir = sourceDir + File.separator + file[i].getName();
                // 准备复制的目标文件夹
                String subTargetDir = targetDir + File.separator + file[i].getName();
                // 复制子目录
                copyDirectiory(subSourceDir, subTargetDir);
            }
        }
    }
    public static void main(String[] args) throws IOException {
    	copyDirectiory("d:/gllsjava","d:/gllsjava2");
	}
}

5.答案参考原题目
6.答案参考原题目 

7.解释下面代码的含义:

while((m=fis.read())!=-1){
				char c = (char) m;
				System.out.print(c);
			}

含义:一个文件输入流fis,每次读取一个字节,将字节以字符形式输出。

六、可选题
1.使用IO包中的类读取D盘上exam.txt文本文件的内容,每次读取一行内容,将每行作为一个输入放入ArrayList的泛型集合中并将集合中的内容使用加强for进行输出显示。

public class Test {
	public static void main(String[] args) throws IOException {
		String path="D:\\exam.txt";
		outputMethod(path);
	}
	public static  void outputMethod(String path) throws IOException {
		List<String> list = new ArrayList<String>(); // 创建集合对象
		// 创建缓冲区对象
BufferedReader br = new BufferedReader(new FileReader(path));	
	    String line = br.readLine(); // 读取数据每次读一行
		while (line != null) {
			list.add(line);
			line = br.readLine();
		}
		br.close();              //关闭
		for(String s:list){
			System.out.println(s);
		}
	}
}

2.假设从入学开始所有书写的Java类代码都在d:/gllsjava文件夹下,包括多级子文件夹。使用IO流获取从入学开始,到目前为止已经写了多少行Java代码。
提示:其实就是获取d:/gllsjava文件夹及其子文件夹下的所有.java文件,使用readLine()读取其中每一行,每读取一行,行数加1。所有的文件读取完毕,得到总共已经写的Java代码行数。需要结合递归实现。
 

public class TestCountDir {
	private int count;
	/**
	 * 统计一个java文件的行数
	 */
    private void countLine(File sourceFile) throws IOException {
        BufferedReader br = null;       
        try {
            // 新建文件输入流
            br = new BufferedReader(new FileReader(sourceFile));
           while(br.readLine()!=null){
        	   count++;
        	   //System.out.println(count);
           }
        } finally {          
             br.close();          
        }
    }
    /**
     * 统计一个目录下所有Java文件的行数
     */
    private void countDir(String sourceDir) throws IOException {
        // 检查源目录
    	File fSourceDir = new File(sourceDir);
    	if(!fSourceDir.exists() || !fSourceDir.isDirectory()){
    		System.out.println("源目录不存在");
    		return;
    	}      		
        // 遍历目录下的文件或目录
        File[] file = fSourceDir.listFiles();
        for (int i = 0; i < file.length; i++) {
            if (file[i].isFile()) {
               if(file[i].getName().toLowerCase().endsWith(".java")){
            	  // System.out.println(file[i].getName());
            	   countLine(file[i]);
               }
            }            
            //递归统计代码行数
            if (file[i].isDirectory()) {
                // 准备统计的文件夹
                String subSourceDir = sourceDir + File.separator + file[i].getName();
                // 统计子目录
                countDir(subSourceDir);
            }
        }
    }
    public static void main(String[] args) throws IOException {
    	
    	TestCountDir tcd = new TestCountDir();
    	tcd.countDir("d:/gllsjava");
    	System.out.println(tcd.count);
	}
}

3.由控制台按照固定格式输入学生信息,包括学号,姓名,年龄信息,当输入的内容为exit退出;将输入的学生信息分别封装到一个Student对象中,再将每个Student对象加入到一个集合中,要求集合中的元素按照年龄大小正序排序;最后遍历集合,将集合中学生信息写入到记事本,每个学生数据占单独一行。

public class Student implements Comparable<Student>{
	private Integer num;
	private String name;
	private Integer age;
	//省略getter和setter方法
	//省略构造方法
	public int compareTo(Student stu) {
		return this.age-stu.age;
	}
	public String toString() {
		return "Student [age=" + age + ", name=" + name + 
", num=" + num + "]";
	}
}
public class Test {
	public static void main(String[] args) {
		Set<Student> stuSet = saveStudentInfo();
		outputInfo(stuSet);
	}
	private static Set<Student> saveStudentInfo() {
		Scanner input = new Scanner(System.in);
		// 保存学生信息的TreeSet集合对象
		Set<Student> stuSet = new TreeSet<Student>();
		while (true) {
			// 输入提示
			System.out.println("请输入学生信息:(学号#姓名#年龄)");
			String inputData = input.nextLine();
			// 判断是否退出 inputData.equals("exit")
			if ("exit".equals(inputData)) {
				break;
			}
			// 将用户输入的学生信息分割为String[]
			String[] info = inputData.split("#");
			// 将输入信息封装到Student对象中
			Student stu = 
new Student(Integer.parseInt(info[0]), info[1],
					Integer.parseInt(info[2]));
			// 将学生对象加入集合
			stuSet.add(stu);
		}
		return stuSet;
	}
	private static void outputInfo(Set<Student> stuSet) {
		File file = new File("e:/student.txt");
		// 创建文件输出流对象
		FileWriter fw = null;
		try {
			fw = new FileWriter(file);
			Iterator<Student> it = stuSet.iterator();
			while (it.hasNext()) {
				String info = it.next().toString();
				// 将info字符串,写入记事本
				fw.write(info);
				// 完成换行功能
				fw.write("\r\n");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				fw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

4、完成目录的copy代码(结合递归算法)。 

public class Test1 {

	public static void main(String[] args) throws Exception {
		copyDir("c:/7/","c:/8/");
	}
	/**
	 * 将srcPath目录下的文件复制到destPath目录下
	 * @param srcPath
	 * @param destPath
	 */
	private static void copyDir(String srcPath,String destPath) throws Exception{
		File f = new File(srcPath);
		if(f.isDirectory()){
			File nF = new File(destPath);
			nF.mkdir();
			File[] files = f.listFiles();
			for (int i = 0; i < files.length; i++) {
				String temp = File.separator + files[i].getName();
				if(files[i].isDirectory()){
					copyDir(srcPath +  temp, destPath + temp);
				}else{
					BufferedInputStream bis = new BufferedInputStream(new FileInputStream(files[i]));
					BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destPath + temp));
					byte [] bytes = new byte[10];
					int len = bis.read(bytes);
					while(len != -1){
						//写出
						bos.write(bytes, 0, len);
						//下一次的读取
						len = bis.read(bytes);
					}
					
					bos.flush();
					bis.close();
					bos.close();
					return;
				}
			}
		}
	}

}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值