实验4 IO

本文提供了一系列Java编程实验,涉及输入输出流的使用,包括通过System.in读取用户输入构建文件路径,使用FileReader读取文件内容并打印,以及实现文件合并和统计文本中字母数量的功能。此外,还演示了如何利用对象输入输出流进行对象的序列化和反序列化。
摘要由CSDN通过智能技术生成

1.实验目的

(1) 掌握输入输出流的总体结构;

(2) 掌握流的概念;

(3) 了解各种流的使用。

2.实验要求

在Eclipse下创建Practice4项目,按照实验题名建包,然后将本题源代码放在同一包下。作业提交时将Practice4项目下src文件包命名为Practice4_姓名.src压缩后提交。

3.实验题目

Exer1:实验题1 阅读下面程序,理解其功能,按题中序号标识进行解释说明,并以注释方式写在代码内部。

import java.io.FileReader;

import java.io.IOException;

public class FileViewer {

/** Defines the entry point of the program. */

public static void main(String[] args) {

System.out.println("Please enter the file path:");

try {

String fileName = "";

while (true) {

int readByte = System.in.read();                             /* 1 */

if (readByte == -1 || readByte == '\r')                      /* 2 */

break;

fileName += (char) readByte;                                 /* 3 */

}

// Reads the file and prints it to the System.out stream.

char[] buffer = new char[20];                                             /* 4 */

FileReader reader = new FileReader(fileName);              /* 5 */

while (true) {

int length = reader.read(buffer);                              /* 6 */

if (length < 0) // Reads a long as there is more data.

break;

String text = new String(buffer, 0, length);              /* 7 */

System.out.print(text);

}

} catch (IOException e) {

e.printStackTrace();

}

}

}

 [基本要求] 运行程序,并写出本题程序关键程序(1-7)的功能,用注释的方式说明在代码内部。

package Exer1;


import java.io.FileReader;
import java.io.IOException;

public class FileViewer {
	
public static void main(String[] args) {
	System.out.println("Please enter the file path:");
	try {
		String fileName = "";
		while (true) {
			int readByte = System.in.read();     
			/* System.in.read()可以实现输入字符,返回字符的Unicode码,只能输入一个字符。
			 * 返回字节值(0-255)之间的一个整数),如果未读出字节就返回-1。 */
			if (readByte == -1 || readByte == '\r')                     
				/* 未读出字节或者回车*/
				break;
			fileName += (char) readByte;                                
			/* 把readByte的值转换成字符型,尾加到filename字符串中去。*/
		}
		
		char[] buffer = new char[20];                                             
		/* 定义一个大小为20的字符数组 */
		FileReader reader = new FileReader(fileName);             
		/* 定义一个文件字符输入流 */
		while (true) {
			int length = reader.read(buffer);                              
			/* reader调用read方法,读取文件中buffer.length个字符到字符数组buffer中,
			 * 并返回实际读到的字符数目,将其赋值给length */
			if (length < 0) 
					break;
			String text = new String(buffer, 0, length);           
			/* 提取字符数组buffer中的一部分字符创建一个String对象,起始位置在buffer的0号位置
			 * ,提取length个字符,即将buffer字符数组中的全部字符提取,创建一个字符串text*/
				System.out.print(text);
		}
	} catch (IOException e) {
		e.printStackTrace();
	}
}
}

编译运行

Please enter the file path:
d:\test.txt
Hello,world!

Exer2设计一个类FileMerge, 实现从一个文件夹(文件夹名称为“poem”,可以从作业管理系统中下载)中依次读取每个文件的内容,然后再写入到文件“李白诗集.txt”中,存储该文件。

[基本要求] 在当前目录中搜索txt文件,不必实现递归搜索。

package Exer2;

import java.io.*;
import java.util.*;
public class FileMerge {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
        File dirFile = new File("d:\\大学实验\\Java\\poem");
        FileAccept fileAccept = new FileAccept();
        fileAccept.setExtendName("txt");
        String fileName[] = dirFile.list(fileAccept);
     
        for(String name:fileName) {
        	System.out.println(name+"的内容为:");
        	File sourceFile = new File("d:\\大学实验\\Java\\poem\\"+name);
        	File targetFile = new File("d:\\大学实验\\Java\\李白诗集.txt");
            try {
                Reader in = new FileReader(sourceFile);
                BufferedReader bufferRead = new BufferedReader(in);
                String s = null;
                while ((s=bufferRead.readLine())!=null) {
                	byte b[] = s.getBytes("iso-8859-1");
                	String content = new String(b,"GB2312");
                	System.out.println(content);
                }
                bufferRead.close();
                in.close();
                
               //  OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(targetFile),"UTF-8");
               // BufferedWriter writer=new BufferedWriter(write);  
               
               Writer out = new FileWriter(targetFile,true);
               BufferedWriter  bufferWrite = new BufferedWriter(out);
            	String s1 = null;
            	while((s1= bufferRead.readLine())!=null) {
            		bufferWrite.write(s1);
            		bufferWrite.newLine();
            	}
            	bufferWrite.close();
               out.close();
            }
            catch(IOException e) {
        	  System.out.println(e.toString());
          }
     
        }
	}

}

Exer3:写一程序统计纯文本文件“input.txt”(可以从作业管理系统中下载)的大写字母、小写字母个数,并将所有小写字母转换为大写字母,输出到result.txt (使用缓冲流)

package Exer3;

import java.io.*;


public class Exer3 {
	public static void main(String args[]) {
		int countD = 0;
		int countX = 0;
		File fread = new File("D:\\大学实验\\Java\\input.txt"); //将filename文件的改成绝对路径就可以了
		File fwrite = new File("D:\\大学实验\\Java\\result.txt");
		try {
			Reader in =new FileReader(fread);
			BufferedReader bufferRead = new BufferedReader(in);
			
			Writer out = new FileWriter(fwrite);
			BufferedWriter bufferWrite = new BufferedWriter(out);
		
			String s =null;
			System.out.println("统计大小写字母:");
			while ((s=bufferRead.readLine())!= null) {
				char c[] = s.toCharArray();
				for(int i=0;i<c.length;i++) {
					if(c[i]>=65 && c[i]<=90) {
						countD++;
					}else if(c[i]>=97 &&c[i]<=122){
						countX++;
					}
				}
				s= s.toUpperCase();
				bufferWrite.write(s);
				bufferWrite.newLine();
			}
			bufferWrite.close();
			out.close();
			bufferRead.close();
			in.close();
		}
		catch(IOException e) {
			System.out.println(e.toString());
		}
		System.out.println("大写字母有:"+countD+",小写字母有:"+countX);
		
	}
}

编译运行

统计大小写字母:
大写字母有:7,小写字母有:74

Exer4:对象输入与输出流(使用对象流)

现有一个Student类:

 

程序实现: 将Student类的2个实例写到文件中student.txt中,并从student.txt 中读取这个实例,运行结果如图所示:

package Exer4;
import java.io.*;

public class Student implements Serializable {
	private static final long serialVersionUID = 1L;
	 /*这个警告一般来讲不影响程序的运行,它的意思是:序列化类XXX 没有声明serialVersionUID,
	 也就是让你在类中设置serialVersionUID的属性。
	 解决办法:手动设置:
	 在类中加上一行,serialVersionUID的值自己设置,我这里写的是1L。*/
	int id;
	String name;
	int age;
	String department;
	public Student(int id, String name,int age,String department) {
		this.id = id;
		this .name= name;
		this.age = age;
		this.department =department;
	}
	public String toString() {
		return "Student [id="+id+",name="+name+",age="+age
				+",department="+department+"]";
	}
}
package Exer4;

import java.io.*;
public class Exer4 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Student Jim = new Student(19,"Jim",50,"Physics");
		File file = new File("D:\\大学实验\\Java\\student.txt");
		try {
			FileOutputStream fileOut = new FileOutputStream(file);
			ObjectOutputStream objectOut = new ObjectOutputStream(fileOut);
			objectOut.writeObject(Jim);
			//objectOut.close();
			FileInputStream fileIn = new FileInputStream(file);
			ObjectInputStream objectIn = new ObjectInputStream(fileIn);
			Student Jones = (Student)objectIn.readObject();
			Jones = new Student(20,"Jones",27,"Maths");
			objectOut.writeObject(Jim);
			System.out.println(Jim.toString());
			System.out.println(Jones.toString());
			objectOut.close();
			objectIn.close();
			
		}
		catch(ClassNotFoundException event) {
			System.out.println("不能读出对象");
		}
		catch(IOException event) {
			System.out.println(event);
		}
	}

}

编译运行

Student [id=19,name=Jim,age=50,department=Physics]
Student [id=20,name=Jones,age=27,department=Maths]

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值