JavaDay20 IO流-练习

1. 运用缓冲流完成文件复制

//1.字节缓冲输入输出流
package com.briup.day21;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class Method1 {
	public static void main(String[] args) throws Exception {
		FileInputStream fis = new FileInputStream("src/com/briup/day21/a.txt");
		BufferedInputStream bis = new BufferedInputStream(fis);
		BufferedOutputStream bos = new BufferedOutputStream(new
		FileOutputStream("src/com/briup/day21/b.txt"));
		int len = -1;
		while ((len = bis.read()) != -1) {
			bos.write(len);
			bos.flush();
		}
		fis.close();
		bis.close();
		bos.close();
	}
}
//2.BufferedReader+PrintStream
package com.briup.day21;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
/**
 * @author chouhan
 */
public class TestBuffered {
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new FileReader("src/com/briup/day21/a.txt"));
		PrintStream ps = new PrintStream("src/com/briup/day21/b.txt");
		String data=null;
		while((data=br.readLine())!=null) {
			ps.println(data);
		}
		br.close();
		ps.close();
	}
}

2. 写PropertiesFile类

  1. 在message文件中存放prop_name=prop_value格式的属性,每行存放一个属性,输入一个属性名,找出其对应的属性值并输出。
//FileReader+BufferedReader
package com.briup.day21;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Scanner;
public class Method2 {
	public static void main(String[] args) throws Exception {
		FileReader fr = new FileReader("src/com/briup/day21/message.properties");
		BufferedReader br = new BufferedReader(fr);
		String len = null;
		System.out.println("请输入你想查找的key值:");
		String name = new Scanner(System.in).nextLine();
		while ((len = br.readLine()) != null) {
			String[] split = len.split("[=]");
			if (name.equals(split[0])) {
				System.out.println(name + "对应的value是:" + split[1]);
			}
		}
	}
}
//BufferedReader+PrintStream
package com.briup.day21;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
 * @author chouhan
 */
public class PropertiesFile {
	public static void main(String[] args) throws IOException {
		//prop_name=prop_value
		BufferedReader br=new BufferedReader(new FileReader("src/com/briup/day21/message.txt"));
		PrintStream ps=new PrintStream("src/com/briup/day21/properties.txt");
		Map<Integer,String> map=new HashMap<Integer,String>();
		int key=1;
//		while((br.readLine())!=null) {
//			map.put(key,br.readLine());
//			key++;
//		}
		//定义len是为了防止读取两次
		String len=null;
		while((len=br.readLine())!=null) {
			map.put(key, len);
			key++;
		}
		Set<Map.Entry<Integer,String>> entrySet=map.entrySet();
		for (Map.Entry<Integer, String> entry : entrySet) {
			ps.println("prop_name:"+entry.getKey()+","+"prop_value:"+entry.getValue());
			//shift+alt+Z:补充try-catch
		}
		br.close();
		ps.close();
	}
}

3. 编程实现:创建Teacher类,属性包含id,name,salary,从控制台输入教师基本信息,数据之间通过“ - ”分割(每一行,为一个老师的信息),当输入exit时结束,从控制台获取教师信息后创建教师对象,将集合写到文件中,再从文件中读取集合进行遍历输出。

package com.briup.day21;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
 * @author chouhan
 */
public class TestTeacher {
	public static void main(String[] args) throws Exception{
		List<Teacher> list = new ArrayList<Teacher>();
		System.out.println("输入exit的时候结束输入");
		System.out.println("请按照id-name-salary的形式输入:");
		// 从控制台输入教师基本信息,数据之间通过“ - ”分割(每一行,为一个老师的信息),当输入exit时结束
		while (true) {
			String str = new Scanner(System.in).nextLine();
			if ("exit".equals(str)) {
				break;
			} else {
				String[] split = str.split("[-]");
				// 从控制台获取教师信息后创建教师对象,将对象添加到集合中
				list.add(new Teacher(Integer.valueOf(split[0]), split[1], Integer.valueOf(split[2])));
			}
		}
		// 将集合写到文件中
		FileOutputStream fos = new FileOutputStream("src/com/briup/day21/teacher.txt");
		ObjectOutputStream oos = new ObjectOutputStream(fos);
		oos.writeObject(list);
		oos.flush();
		// 再从文件中读取集合进行遍历输出
		FileInputStream fis = new FileInputStream("src/com/briup/day21/teacher.txt");
		ObjectInputStream ois = new ObjectInputStream(fis);
		List<Teacher> list1 = (List<Teacher>) ois.readObject();
		for (Teacher t : list1) {
			System.out.println(t);
		}
		fos.close();
		oos.close();
		fis.close();
		ois.close();
	}
}
class Teacher implements Serializable{
	int id;
	String name;
	int salary;
	public Teacher() {
		super();
	}
	public Teacher(int id, String name, int salary) {
		super();
		this.id = id;
		this.name = name;
		this.salary = salary;
	}
	@Override
	public String toString() {
		return "Teacher [id=" + id + ", name=" + name + ", salary=" + salary + "]";
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getSalary() {
		return salary;
	}
	public void setSalary(int salary) {
		this.salary = salary;
	}
	/**
	 * 1.用于区分类,如果不写会有默认值,但是再添加属性时,序列号会改变,
	 * 2.就会出现序列号不匹配的情况,所以写上这个属性值
	 */
	private static final long serialVersionUID = 1L;
}

4.文件a中的内容为:java version "* **"Java™ SE Runtime Environment (build 1.8.0_301-b09)Java HotSpot™ 64-Bit Server VM (build 25.301-b09, mixed mode)新内容为:1.8.0_301

/* 1.文件a中的内容为:java version "* **"Java(TM) SE Runtime Environment (build 1.8.0_301-b09)Java HotSpot(TM) 64-Bit Server VM (build 25.301-b09, mixed mode),要求:读取文件a的内容,并输出到另外一个文件里面,把* **换成新内容再输出,新内容为:1.8.0_301
 * 文件字节输入流+转换输入流+字符缓冲输入流->读取文件
 * 字符缓冲输出流+转换输出流+文件字节输出流->写出文件
 * 缓冲流中操作替换
 */
package com.briup.day21;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class Method3 {
	public static void main(String[] args) throws Exception {
		FileInputStream fis = new FileInputStream("src/com/briup/day21/aa.txt");
		InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
		BufferedReader br = new BufferedReader(isr);
		FileOutputStream fos = new FileOutputStream("src/com/briup/day21/bb.txt");
		OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
		BufferedWriter bw = new BufferedWriter(osw);
		String str = "1.8.0_301";
		String len = null;
		while ((len = br.readLine()) != null) {
			if (len.equals("***** ******")) {
				bw.write(str);
			} else {
				bw.write(len + "\n");
			}
		}
		bw.flush();
		fis.close();
		isr.close();
		br.close();
		fos.close();
		osw.close();
		bw.close();
	}
}
//2.直接用字符流进行操作
package com.briup.day20;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
/**
 * @author chouhan
 */
public class TestReplace {
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new FileReader("src/com/briup/day20/a.txt"));
		BufferedWriter bw=new BufferedWriter(new FileWriter("src/com/briup/day20/a2.txt"));
		String s = null;
		while((s=br.readLine())!=null){
			if(s.contains("* **")) {
				String str=s.replace("* **","1.8.0_301");
				bw.write(str);
				bw.newLine();
			}else {
				bw.write(s);
				bw.newLine();
			}
			bw.flush();
		}
		br.close();
		bw.close();
	}
}

5.RandomAccessFile随机访问流的特点

  1. 对象既可以读也可以写;
  2. 随机定位文件中的任意字节位置进行读或者写,并且可以前后反复定位;
  3. 创建该类的对象时,需要指定要操作的文件和操作的模式。

6.运用RandomAccessFile流向指定文件r.txt中的指定位置添加内容:文件内容aacc,往aacc中间添加两个字母bb。

package com.briup.day21;
import java.io.ByteArrayOutputStream;
import java.io.RandomAccessFile;
public class Method4 {
	public static void main(String[] args) throws Exception {
		// 随机定位文件中的任意字节位置进行读或者写,并且可以前后反复定位;
		RandomAccessFile raf = new RandomAccessFile("src/com/briup/day21/r.txt", "rw");
		// 指定要放入位置
		int index = 2;
		// 指定要插入的内容
		String str = "bb";
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] buf = new byte[1024];
		int len = -1;
		// 定位到要插入数据的位置,准备去读此位置以及之后位置的数据,并写入到数据中保存
		raf.seek(index);
		while ((len = raf.read(buf)) != -1) {
			baos.write(buf, 0, len);
		}
		baos.flush();
		// 再次定位到要插入的位置,准备去写内容,以及临时保存的内容
		// 默认覆盖
		raf.seek(index);
		raf.write(str.getBytes());
		// 写入刚刚临时保存的内容
		raf.write(baos.toByteArray());
		// 关闭流
		baos.flush();
		raf.close();
		baos.close();
	}
}

7.写一个方法,输入一个文件名和一个字符串,统计这个字符串在这个文件中出现的次数。

//1.文件字符输入流+Scanner控制台输入
package com.briup.day21;
import java.io.FileReader;
import java.util.Scanner;
public class Method5 {
	public static void main(String[] args) {
		int count = count();
		System.out.println("出现的次数为" + count);
	}

	public static int count() {
		System.out.println("请输入文件名:");
		String filename = new Scanner(System.in).nextLine();
		System.out.println("请输入你想查询的字符串:");
		String str = new Scanner(System.in).nextLine();
		FileReader fr = null;
		int count = 0;
		try {
			for (int i = 0; i < str.length(); i++) {
				fr = new FileReader(filename);
				char[] ch = new char[str.length()];
				fr.skip(i);
				int len = -1;
				while ((len = fr.read(ch)) != -1) {
					String newStr = new String(ch, 0, len);
					if (str.equals(newStr)) {
						count++;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fr != null) {
				try {
					fr.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return count;
	}
}
//2.控制台输入->读取字节->缓冲流保存数据->文件读取
package com.briup.day21;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
/**。
 * @author chouhan
 */
public class Test2 {
	public static void main(String[] args) throws IOException {
		InputStreamReader ir = new InputStreamReader(System.in);
	    BufferedReader br = new BufferedReader(ir);
	    System.out.println("请输入文件名:");
	    String path = br.readLine();
	    System.out.println("请输入要读入的字符串:");
	    String str = br.readLine();
	    //把缓冲流中的字符串全部转换成字符数组
	    char[] arr = str.toCharArray();//字符串数组
	    //文件读取
	    FileReader fr = null;
	    //定义另一个字符数组存放读取出来的字符
	    char[] arr2 = new char[arr.length];
	    int count = 0;
	    for (int i = 0; i < arr.length; i++) {
	        fr = new FileReader(path);
	        int data = -1;
	        fr.skip(i);
	        while ((data = fr.read(arr2, 0, arr.length)) != -1) {
	            //比较两个字符数组,字符串相同就把它的出现次数++
	            if (Arrays.equals(arr, arr2)) {
	                count++;
	            }
	            System.out.println(Arrays.toString(arr2));
	        }
	    }
	    System.out.println(count);
	}
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值