java学习之路 之 IO流-练习题

package com.atguigu.javae.io;

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

import org.junit.Test;

public class IOTest {
	
	@Test
	public void testReader() {
		// 1) 声明流对象引用,并赋值为null;
		FileReader fReader = null;
		// 2) try catch finally
		try {
			// 5) 创建流对象, 建立通道
			fReader = new FileReader("一个文本文件"); // 尝试从当前目录下开始找这个文件
			// 6) 通过流对象,处理数据
			int ch = fReader.read();
			while (ch != -1) {
				// 1) 处理已经读到的数据
				System.out.print((char)ch); // 如果包含换行, 也能正确处理
				// 2) 继续读后面的数据, 直到-1为止
				ch = fReader.read();
			}
		} catch (Exception e) {
			// 4) 处理异常
			e.printStackTrace();
		} finally {
			// 3) 关闭流对象
			if (fReader != null) {
				try {
					fReader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

class FileCopy {
	// 使用文件流完成文件的复制,每一次读取一个字节
	@Test
	public void test() {
		
		FileReader fr = null;
		FileWriter fw = null;
		
		try {
			fr = new FileReader("./src/com/atguigu/javase/io/Filecopy.java");
			fw = new FileWriter("Filecopy.java.bak");
			
			int ch = fr.read();
			while (ch != -1) {
				fw.write(ch);
				ch = fr.read();
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fr != null) {
				try {
					fr.close();
				} catch (Exception e2) {
				}
			}
			if (fw != null) {
				try {
					fw.close();
				} catch (Exception e2) {
				}
			}
		}
	}
}

class IOTest {
	// 使用问件输入流 读取文件内容,并给没行前加上行号,然后在控制台打印输出,
	public static void main(String[] args) {
		FileReader fr = null;
		
		try {
			fr = new FileReader("./src/com/atguigu/javase/io/IOTest.java");
			char[] buf = new char[100]; 
			int ch = fr.read(buf);
			System.out.println(buf);
			int count = 1;
			System.out.print(count++ + " ");
			while (ch != -1) {
				for (int i = 0; i < ch; i++) {
					System.out.print(buf[i]);
					if (buf[i] == '\n') {
						System.out.print(count++ + " ");
					} 
				}
				ch = fr.read(buf);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fr != null) {
				try {
					fr.close();
				} catch (Exception e2) {
				}
			}
		}
	}
}

class TestCopy {

	public static void main(String[] args) {
		FileReader fReader = null;
		FileWriter fWriter = null;
		// 使用文件流完成文件的复制,每一次读取100个字节
		try {
			fReader = new FileReader("./src/com/atguigu/javase/io/TestCopy.java");
			fWriter = new FileWriter("TestCopy.java.bak");
			
			char[] buf = new char[100];
			int realCount = fReader.read(buf);
			
			while(realCount != -1) {
				fWriter.write(buf, 0, realCount);
				realCount = fReader.read(buf);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fReader != null) {
				try {
					fReader.close();
				} catch (Exception e2) {
				}
			}
			if (fWriter != null) {
				try {
					fWriter.close();
				} catch (Exception e) {
				}
			}
		}
	}
}

class TestFileCopy2 {
	// 使用缓冲流完成文件的复制
	public static void main(String[] args) {
		FileReader fReader = null;
		BufferedReader bReader = null;
		FileWriter fWriter = null;
		BufferedWriter bWriter = null;
		
		try {
			fReader = new FileReader("./src/com/atguigu/javase/io/TestCopy.java");
			bReader = new BufferedReader(fReader);
			fWriter = new FileWriter("TestFileCopy2.java.bak2");
			bWriter = new BufferedWriter(fWriter);
			
			String line = bReader.readLine();
			while (line != null) {
				
				bWriter.write(line);
				bWriter.newLine();
				line = bReader.readLine();
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (bReader != null) {
				try {
					bReader.close();
				} catch (Exception e2) {
				}
			}
			if (bWriter != null) {
				try {
					bWriter.close();
				} catch (Exception e2) {
					// TODO: handle exception
				}
			}
		}
	}
}

package com.atguigu.javase.io;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Set;
import java.util.TreeSet;

import org.junit.Test;

public class Work {
	
	@Test
	public void work6() {
		//把xmlstudy文件中的内容的重复的行去掉, 并对行进行从小到大排序后 写入新文件xmlstudy2中, 验证文件中有没有去掉空行,并且排序
		FileReader fileReader = null;
		BufferedReader bufferedReader = null;
		FileWriter fileWriter = null;
		BufferedWriter bufferedWriter = null;
		try {
			fileReader = new FileReader(new File("xmlstudy"));
			bufferedReader = new BufferedReader(fileReader);
			fileWriter = new FileWriter(new File("xmlstudy2"));
			bufferedWriter = new BufferedWriter(fileWriter);
			
			Set<String> set = new TreeSet<String>();
			String line = null;
			while ((line = bufferedReader.readLine()) != null) {
				set.add(line);
			}
			for (String string : set) {
				bufferedWriter.write(string);
				bufferedWriter.newLine();
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			try {
				bufferedReader.close();
			} catch (Exception e2) {
				// TODO: handle exception
			}
			try {
				bufferedWriter.close();
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
	}
	
	@Test
	public void work1() {
		// 使用Object输入输出流,写入50个100以内的随机整数, 再读出来打印输出
		FileOutputStream fos = null;
		BufferedOutputStream bos = null;
		ObjectOutputStream oos = null;
		try {
			fos = new FileOutputStream("50个随机数");
			bos = new BufferedOutputStream(fos);
			oos = new ObjectOutputStream(bos);
			for (int i = 0; i < 50; i++) {
				oos.writeInt((int)(Math.random() * 100));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				oos.close();
			} catch (Exception e2) {
			}
		}
	}
	
	@Test
	public void work2() {
		FileInputStream fis = null;
		BufferedInputStream bis = null;
		ObjectInputStream ois = null;
		try {
			fis = new FileInputStream("50个随机数");
			bis = new BufferedInputStream(fis);
			ois = new ObjectInputStream(bis);
			for (int i = 0; i < 50; i++) {
				System.out.println(ois.readInt());
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				ois.close();
			} catch (Exception e2) {
			}
		}
	}
			
	//扩展 写入随机个100以内的随机整数, 再全部读出来打印输出
	@Test
	public void work3() {
		// 使用Object输入输出流,写入50个100以内的随机整数, 再读出来打印输出
		FileOutputStream fos = null;
		BufferedOutputStream bos = null;
		ObjectOutputStream oos = null;
		try {
			fos = new FileOutputStream("随机个随机数");
			bos = new BufferedOutputStream(fos);
			oos = new ObjectOutputStream(bos);
			int rand = (int)(Math.random() * 50);
			oos.writeInt(rand);
			for (int i = 0; i < rand; i++) {
				oos.writeInt((int)(Math.random() * 100));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				oos.close();
			} catch (Exception e2) {
			}
		}
	}
	
	@Test
	public void work4() {
		FileInputStream fis = null;
		BufferedInputStream bis = null;
		ObjectInputStream ois = null;
		try {
			fis = new FileInputStream("随机个随机数");
			bis = new BufferedInputStream(fis);
			ois = new ObjectInputStream(bis);
			int count = ois.readInt();
			for (int i = 0; i < count; i++) {
				System.out.println(ois.readInt());
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				ois.close();
			} catch (Exception e2) {
			}
		}
	}
}

package com.atgiugu.javase.io;

import java.io.FileReader;
import java.io.FileWriter;

public class FileCopy {
	
	public static void main(String[] args) {
		// 把FileCopy.java复制成FileCopy.java.bak
		FileReader fReader = null;
		FileWriter fWriter = null;
		try {
			fReader = new FileReader("./src/com/atgiugu/javase/io/FileCopy.java");
			fWriter = new FileWriter("FileCopy.java.bak");
			int ch = fReader.read();
			while (ch != -1) {
				// 1) 处理已经读到的数据
				fWriter.write(ch);
				// 2) 继续读后面的数据,直到-1
				ch = fReader.read();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fReader != null) {
				try {
					fReader.close();
				} catch (Exception e2) {
				}
			}
			
			if (fWriter != null) {
				try {
					fWriter.close();
				} catch (Exception e2) {
				}
			}
		}
	}
}	

package com.atgiugu.javase.io;

import java.io.FileReader;
import java.io.FileWriter;

public class TextFileCopy {
	
	public static void main(String[] args) {
		//编写程序TextFileCopy.java,在测试方法中,将TextFileCopy.java复制为TextFileCopy.java.bak文件;
		FileReader fReader = null;
		FileWriter fWriter = null;
		try {
			//fReader = new FileReader("真的爱你.mp3"); 不可以处理二进制文件
			//fWriter = new FileWriter("真的不爱你.mp3");
			fReader = new FileReader("TextFileCopy.java");
			fWriter = new FileWriter("TextFileCopy.java.bak");
			char[] buf = new char[100];
			int realCount = fReader.read(buf);
			while (realCount != -1) {
				// 1) 处理已经读到的数据
				fWriter.write(buf, 0, realCount);
				// 2) 继续读后面的数据
				realCount = fReader.read(buf);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fReader != null) {
				try {
					fReader.close();
				} catch (Exception e2) {
				}
			}
			if (fWriter != null) {
				try {
					fWriter.close();
				} catch (Exception e2) {
				}
			}
		}
	}
}

package com.atguigu.javase.work;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import org.junit.Test;

public class HomeWork {
	
	//请把学生名与考试分数录入到Map中,并按分数显示前三名成绩学员的名字。
	@Test
	public void work1() {
		Map<String, Integer> map = new HashMap<String, Integer>();
		map.put("小明", 80);
		map.put("小花", 70);
		map.put("小丽", 60);
		map.put("小强", 100);
		map.put("小伟", 99);
		map.put("小刚1", 100);
		map.put("小刚2", 100);
		map.put("小刚3", 100);
		map.put("小刚4", 100);
		map.put("小刚5", 100);
		
		Set<String> nameSet = map.keySet();
		String[] nameArr = nameSet.toArray(new String[0]);
		for (int i = 0; i < nameArr.length - 1; i++) {
			for (int j = 0; j < nameArr.length - 1 - i; j++) {
				if (map.get(nameArr[j]) > map.get(nameArr[j + 1])) {
					String tmp = nameArr[j];
					nameArr[j] = nameArr[j + 1];
					nameArr[j + 1] = tmp;
				}
			}
		}
		Set<Integer> high3 = new TreeSet<Integer>();
		for (int i = nameArr.length - 1; i >= 0 ; i--) {
			if (high3.size() == 3) {
				break;
			}
			high3.add(map.get(nameArr[i]));
		}
		List<Integer> high3List = new ArrayList<Integer>();
		high3List.addAll(high3);
		int no1count = 0;
		int no2count = 0;
		for (int i = nameArr.length - 1; i >= 0 ; i--) {
			if (map.get(nameArr[i]) == high3List.get(2)) {
				System.out.println(nameArr[i] + " : " + high3List.get(2));
				no1count++; // 最高分个数++
			} else if (map.get(nameArr[i]) == high3List.get(1)) {
				if (no1count >= 3) { // 如果是最高分个数已经大于3 中断第二高分的同学的打印
					break;
				}
				System.out.println(nameArr[i] + " : " + high3List.get(1));
				no2count++; // 第二高分计数
			} else if (map.get(nameArr[i]) == high3List.get(0)) {
				if (no1count + no2count >= 3) {
					break;
				}
				System.out.println(nameArr[i] + " : " + high3List.get(0));
			}
		}
		//System.out.println(nameArr[nameArr.length - 1] + " : " + map.get(nameArr[nameArr.length - 1]));
		//System.out.println(nameArr[nameArr.length - 2] + " : " + map.get(nameArr[nameArr.length - 2]));
		//System.out.println(nameArr[nameArr.length - 3] + " : " + map.get(nameArr[nameArr.length - 3]));
	}
	
	@Test
	public void work2() {
		Map<String, Integer> map = new HashMap<String, Integer>();
		map.put("小明", 80);
		map.put("小花", 70);
		map.put("小丽", 60);
		map.put("小强", 100);
		map.put("小伟", 99); // 99小伟
		map.put("小刚", 100);// 100小刚
		
		List<String> list = new ArrayList<String>();
		Set<String> name = map.keySet();
		for (String n : name) {
			int score = map.get(n);
			list.add((char)score + n);
		}
		Collections.sort(list);
		Collections.reverse(list);
		System.out.println((int)list.get(0).charAt(0) + " : " + list.get(0).substring(1));
		System.out.println((int)list.get(1).charAt(0) + " : " + list.get(1).substring(1));
		System.out.println((int)list.get(2).charAt(0) + " : " + list.get(2).substring(1));
	}
}


package com.guigu.javase.Object;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import org.junit.Test;

@SuppressWarnings("serial")
class Student implements Serializable{
	
	private int id;
	private String name;
	private double score;
	
	public Student() {
	}

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

	@Override
	public String toString() {
		return "Student [id=" + id + ", name=" + name + ", score=" + score
				+ "]";
	}
}

public class IOTest {
	// 使用对象流将,存有3个学生对象的Set集合对象,写如文件“对象序列化文件”
	@Test
	public void test1() {
		FileOutputStream fos = null;
		ObjectOutputStream oos = null;
		
		try {
			fos = new FileOutputStream("对象序列化文件");
			oos = new ObjectOutputStream(fos);
			
			Student s1 = new Student(1, "小明", 90);
			Student s2 = new Student(2, "小红", 89);
			Student s3 = new Student(3, "小丽", 98);
			
			Set<Student> set = new HashSet<Student>();
			set.add(s1);
			set.add(s2);
			set.add(s3);
			
			oos.writeObject(set);
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				oos.close();
			} catch (Exception e2) {
			}
		}
	}
	
	// 将上述文件内的对象读取出来并在控制台打印输出
	@Test
	public void test2() {
		FileInputStream fis = null;
		ObjectInputStream ois = null;
		
		try {
			fis = new FileInputStream("对象序列化文件");
			ois = new ObjectInputStream(fis);
			
			@SuppressWarnings("unchecked")
			Set<Student> set = (Set<Student>)ois.readObject(); 
			Iterator<Student> iterator = set.iterator();
			while (iterator.hasNext()) {
				System.out.println(iterator.next());
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			try {
				ois.close();
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
	}
	
	// 使用转换流将几个字符串以UTF8编码写入“转换流写文件”文件中
	@Test
	public void test3() {
		FileOutputStream fis = null;
		OutputStreamWriter osw = null;
		
		try {
			fis = new FileOutputStream("转换流写文件");
			osw = new OutputStreamWriter(fis,"UTF8");
			
			osw.write("abdcssd\n");
			osw.write("你管我写什么?");
			osw.write(10);
			osw.write("哈哈哈!!");
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			try {
				osw.close();
			} catch (Exception e2) {
			}
		}
	}
	
	// 使用转换流将“转换流写文件”中的字符串按照UTF8格式读出来并在控制台上打印输出
	@Test
	public void test4() {
		FileInputStream fis = null;
		InputStreamReader isr = null;
		
		try {
			fis = new FileInputStream("转换流写文件");
			isr = new InputStreamReader(fis,"UTF8");
			
			int count = isr.read();
			while (count != -1) {
				
				System.out.print((char)count);
				count = isr.read();
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			try {
				isr.close();
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
	}
	
	获取键盘输入的字符串,并在控制台打印输出,若不是数字则提示
	@Test
	public void test5() {
		InputStreamReader isr = null;
		BufferedReader brReader = null;
		FileWriter fw = null;
		BufferedWriter brWriter = null;
		try {
			isr = new InputStreamReader(System.in); //转换流获取键盘输入的字符串
			brReader = new BufferedReader(isr); // 缓冲流
			fw = new FileWriter("nums.txt");  // 文件输出流
			brWriter = new BufferedWriter(fw); // 缓冲流
			
			for (int i = 0; i < 10;i++) {
				String num = brReader.readLine();
				try {
					Double.parseDouble(num);
					brWriter.write(num);
					brWriter.newLine();
				} catch (NumberFormatException e) {
					System.out.println("输入数字错误!!");
					i--;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				brReader.close();
			} catch (Exception e2) {
			}
			try {
				brWriter.close();
			} catch (Exception e2) {
			}
		}
	}
	
	// 随机访问文件类练习
	@Test
	public void test6() {
		RandomAccessFile raf = null;
		try {
			raf = new RandomAccessFile("随机访问文件", "rw");
			for (int i = 0; i < 26; i++) {
				raf.write('a' + i);
			}
			raf.seek(0);
			for (int i = 0; i < 10; i++) {
				raf.write('A' + i);
			}
			raf.seek(raf.length() - 10);
			for (int i = 0; i < 10; i++) {
				raf.write('0' + i);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			try {
				raf.close();
			} catch (Exception e2) {
			}
		}
	}
	
	// File类的练习
	@Test
	public void test7() {
		File file = new File(".");
		File file1 = new File("xxx");
		
		String[] childFileName = file.list();
		for (int i = 0; i < childFileName.length; i++) {
			System.out.println(childFileName[i]);
		}
		
		file1.mkdir();
		File file2 = new File("xxx/file.info");
		FileWriter fWriter = null;
		try {
			fWriter = new FileWriter(file2);
			File[] childFiles = file.listFiles();
			for (int i = 0; i < childFiles.length; i++) {
				fWriter.write(childFiles[i].getName() + ",");;
				fWriter.write(childFiles[i].length() + "\n");;
				System.out.print(childFiles[i].getAbsolutePath());
				System.out.println(childFiles[i].length());
			}
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			try {
				fWriter.close();
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		
	}
}


package com.atguigu.javase.io;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.RandomAccessFile;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import org.junit.Test;

class Person implements Serializable {
	
	private static final long serialVersionUID = -402328197027L;

	public static int no = 100; // 静态属性不可以被序列化
	
	private String name;
	private transient int age; // transient是短暂的,瞬时的. 这个属性也不能被序列化
	private String gender;
	//private double weight;
	
	public Person() {
	}

	public Person(String name, int age, String gender) {
		super();
		this.name = name;
		this.age = age;
		this.gender = gender;
	}

	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + ", gender=" + gender
				+ "]";
	}
	
}

/**
 * 写一个Student类 ,包含属性 id, name, score
 * 序列化一个包含3个对象的数组, 再序列化一个包含4个对象的List集合
 * 再反序列化,打印输出
 */
public class IOTest {
	
	@Test
	public void exer5() {
		// 创建目录xxx
		File file = new File("xxx");
		file.mkdir();
		// 列出当前目录下的所有子文件和子目录, 把文件的文件名和文件长度信息写入文件xxx/file.info中
		File currentDir = new File(".");
		File[] childFiles = currentDir.listFiles();
		FileWriter fileWriter = null;
		try {
			fileWriter = new FileWriter("xxx/file.info");
			for (int i = 0; i < childFiles.length; i++) {
				System.out.println(childFiles[i]);
				fileWriter.write(childFiles[i].getName() + "," + childFiles[i].length());
				fileWriter.write(10);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			try {
				fileWriter.close();
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		
	}
	
	@Test
	public void testFile2() throws IOException {
		File file = new File("abc");
		System.out.println("file.mkdir():" + file.mkdir());
		System.out.println("file.canRead():" + file.canRead());
		System.out.println("file.getAbsolutePath():" + file.getAbsolutePath());
		System.out.println("file.getFreeSpace():" + file.getFreeSpace());
		System.out.println("file.getTotalSpace():" + file.getTotalSpace());
		System.out.println("file.lastModified():" + file.lastModified());
		System.out.println("file.length():" + file.length());
		System.out.println("file.canWrite():" + file.canWrite());
		System.out.println("file.createNewFile():" + file.createNewFile());
		System.out.println("file.exists():" + file.exists());
		System.out.println("file.isDirectory():" + file.isDirectory());
		System.out.println("file.isFile():" + file.isFile());
		// 目录特有的方法
		System.out.println("------------------------");
		String[] childFileNames = file.list();
		for (int i = 0; i < childFileNames.length; i++) {
			System.out.println(childFileNames[i]);
		}
		System.out.println("------------------------");
		// 重点方法
		File[] childFiles = file.listFiles();
		for (int i = 0; i < childFiles.length; i++) {
			System.out.println(childFiles[i].length() + " " + childFiles[i].getAbsolutePath());
		}
		
	}
	@Test
	public void testFile() throws IOException {
		File file = new File("nums.txt");
		System.out.println("file.canRead():" + file.canRead());
		System.out.println("file.getAbsolutePath():" + file.getAbsolutePath());
		System.out.println("file.getFreeSpace():" + file.getFreeSpace());
		System.out.println("file.getTotalSpace():" + file.getTotalSpace());
		System.out.println("file.lastModified():" + file.lastModified());
		System.out.println("file.length():" + file.length());
		System.out.println("file.canWrite():" + file.canWrite());
		System.out.println("file.createNewFile():" + file.createNewFile());
		System.out.println("file.exists():" + file.exists());
		System.out.println("file.isDirectory():" + file.isDirectory());
		System.out.println("file.isFile():" + file.isFile());
		//System.out.println("file.delete():" + file.delete());
	}
	
	
	// 写一个文件, 写入26个小写字母
	@Test
	public void exer3() {
		RandomAccessFile raf = null;
		try {
			raf = new RandomAccessFile("随机文件2", "rw");
			for (int i = 0; i < 26; i++) {
				raf.write('a' + i); // 0x00000061
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			try {
				raf.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	// 再打开这个文件, 把前10个换成大写字母,后10个替换为数字字符
	@Test
	public void exer4() {
		RandomAccessFile raf = null;
		try {
			raf = new RandomAccessFile("随机文件2", "rw");
			//abcdefghijklmn...xyz
			raf.seek(0);
			for (int i = 0; i < 10; i++) {
				raf.write('A' + i);
			}
			raf.seek(raf.length() - 10);
			for (int i = 0; i < 10; i++) {
				raf.write('0' + i);
			}
			//raf.setLength(1024 * 1024 * 1024);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			try {
				raf.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	@Test
	public void testRandomAccessFile() {
		RandomAccessFile raf = null;
		try {
			raf = new RandomAccessFile("随机访问文件", "rw"); // 以读写方式打开文件, 指针指向0下标处
			char ch = (char)raf.read(); // 读一个字节, 一个字节正好是一个英语字符, 指针要作相应的移动
			System.out.println(ch);
			//raf.readChar();
			System.out.println("pointer:" + raf.getFilePointer());
			
			raf.seek(4);
			byte[] buf = new byte[8192];
			int realCount = raf.read(buf, 0, 4); // 只读4个字节
			String string = new String(buf, 0, realCount);
			System.out.println(string);
			
			raf.seek(20);
			realCount = raf.read(buf, 0, 3); // 只读3个字节
			String string2 = new String(buf, 0, realCount);
			System.out.println(string2);
			
			raf.seek(8);
			raf.writeUTF("XXXX");
			//raf.write('a'); 把一个字符当作字节写入文件

			
			// 打开文件,确认内容
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			try {
				raf.close();
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
	}
	
	@Test
	public void testSystemOut2() throws FileNotFoundException {
		System.out.println("aaaaa");
		System.err.println("bbbbb"); // System.err对象中的方法是在另外一个线程中运行
	}
	
	@Test
	public void testSystemOut() throws FileNotFoundException {
		//System.setOut(new PrintStream(new FileOutputStream("sysout"))); // 输入输出重定向
		//System.out.println("abcdefg");
		
		System.setErr(new PrintStream(new FileOutputStream("syserr"))); //把错误输出重定向到文件
		System.err.println("xxxxxxxxx");
		try {
			String string = null;
			System.out.println(string.length());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	// 从键盘获取10组数字, 把这10个数字保存在文件nums.txt中.
	@Test
	public void exer1() {
		// 如果获取到的输入不是数字,则不允许写入文件.
		InputStreamReader isr = null;
		BufferedReader bufferedReader = null;
		FileWriter fileWriter = null;
		BufferedWriter bufWriter = null;
		try {
			isr = new InputStreamReader(System.in);
			bufferedReader = new BufferedReader(isr);
			fileWriter = new FileWriter("nums.txt", true); // 以追加的方式写文件
			bufWriter = new BufferedWriter(fileWriter);
			
			for (int i = 0; i < 10; i++) {
				String str = bufferedReader.readLine();
				try {
					Double.parseDouble(str);
					bufWriter.write(str);
					bufWriter.newLine();
				} catch (NumberFormatException e) {
					System.out.println("输入的数字有误!!");
					i--;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				bufferedReader.close();
			} catch (Exception e2) {
				// TODO: handle exception
			}
			try {
				bufWriter.close();
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
	}
	
	// 使用转换流获取键盘输入的字符串并在控制台打印输出
	@Test
	public void testSystemIn() {
		//System.out.println(System.in);
		InputStreamReader isr = null;
		BufferedReader bufReader = null;
		try {
			isr = new InputStreamReader(System.in); // System.in是一个常量对象, 由JVM自动创建, 我们只需要拿来使用即可
			bufReader = new BufferedReader(isr);
			String line = bufReader.readLine();
			while (line != null) {
				// 1)
				System.out.println(line);
				// 2) 
				line = bufReader.readLine(); // ctrl+z会使得返回null
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			try {
				bufReader.close();
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
	}
	
	@Test
	public void testOutputStreamWriter() {
		FileOutputStream fos = null;
		OutputStreamWriter osw = null;
		try {
			fos = new FileOutputStream("使用转换流写文本文件3", true);
			//osw = new OutputStreamWriter(fos); // 以本地编码方式写文本文件
			osw = new OutputStreamWriter(fos, "UTF8"); // 以指定编码方式写文本文件
			osw.write("来一个字符串");
			osw.write(10);
			osw.write("abcdefgh\n");
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			try {
				osw.close();
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
	}
	// 写一个文本文件,使用UTF8编码方式, 用记事本打开查看内容
	// 再读取文件内容并打印输出
	// 试一下使用ISO8859-1编码方式,写文件并读文件
	@Test
	public void testInputStreamReader() {
		//FileReader fReader = null;
		FileInputStream fis = null;
		InputStreamReader isr = null;
		BufferedReader bufReader = null;
		try {
			//fReader = new FileReader("utf8编码的文本文件.txt"); // 只能使用默认的GBK方式读文本文件
			fis = new FileInputStream("使用转换流写文本文件2");
			//isr = new InputStreamReader(fis); // 默认按照GBK方式把字节流转换为字符流
			isr = new InputStreamReader(fis, "UTF8"); // 以UTF8编码方式把字节流转化为字符流
			bufReader = new BufferedReader(isr);
			String line = bufReader.readLine(); // 直接从流中读一行字符串, line中不包含任何换行
			while (line != null) {
				// 1) 处理数据
				System.out.println(line);
				// 2) 继续读
				line = bufReader.readLine();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 关闭流, 只需要关闭高级流即可
			if (bufReader != null) {
				try {
					bufReader.close();
				} catch (Exception e2) {
				}
			}
		}
	}
	
	// 处理对象, 对象序列化 : 把在GC区中对象的相关数据保存到输出流中.
	// 可以直接序列化类实现了Seriliable接口的对象, 还可以序列化对象数组, 对象集合
	// 序列化和序列化时类的版本要求一致.
	@Test
	public void testSerialize() {
		FileOutputStream fos = null;
		ObjectOutputStream oos = null;
		try {
			fos = new FileOutputStream("对象序列化文件");
			oos = new ObjectOutputStream(fos);
			// 对象序列化
			Person.no = 1000;
			Person obj1 = new Person("张三", 30 , "男");
			Person obj2 = new Person("李四", 40 , "女");
			Person obj3 = new Person("王五", 50 , "男");
			
			Person[] arr = {obj1, obj2, obj3};
			
			/*
			oos.writeObject(obj1);
			oos.writeObject(obj2);
			oos.writeObject(obj3);
			*/
			
			//oos.writeObject(arr);
			
			Set<Person> set = new HashSet<Person>();
			set.add(obj1);
			set.add(obj2);
			set.add(obj3);
			
			oos.writeObject(set);
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			try {
				oos.close();
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
	}
	
	// 对象反序列化 : 把输入流中二进制数据还原成对象的过程
	@Test
	public void testDeSerialize() {
		FileInputStream fis = null;
		ObjectInputStream ois = null;
		try {
			fis = new FileInputStream("对象序列化文件");
			ois = new ObjectInputStream(fis);
			/*
			Person person1 = (Person)ois.readObject();
			System.out.println(person1);
			Person person2 = (Person)ois.readObject();
			System.out.println(person2);
			Person person3 = (Person)ois.readObject();
			System.out.println(person3);
			*/
			
			/*
			Person[] arr = (Person[])ois.readObject();
			for (int i = 0; i < arr.length; i++) {
				System.out.println(arr[i]);
			}
			*/
			Set<Person> set = (Set<Person>)ois.readObject();
			Iterator<Person> iterator= set.iterator();
			while (iterator.hasNext()) {
				Person person = iterator.next();
				System.out.println(person);
			}
			System.out.println(Person.no);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			try {
				ois.close();
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
	}
}

package com.atguigu.javase.work;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

import org.junit.Test;
// 从键盘读取一个字符串,判断是整数,还是浮点数,或者是字符串,然后在控制台上打印输出
public class HomeWork {
	
	@Test
	public void test3() {
		Scanner scanner = null;
		try {
			scanner = new Scanner(System.in);
			/*
			while (scanner.hasNextLine()) {
				String string = scanner.nextLine();
				System.out.println(string);
			}*/
			// aaa 111 222.3 bbb ccc 999
			while (scanner.hasNext()) {
				if (scanner.hasNextInt()) {
					int num = scanner.nextInt();
					System.out.println("整数:" + num);
				} else if (scanner.hasNextDouble()) {
					double value = scanner.nextDouble();
					System.out.println("浮点数:" + value);
				} else {
					String string = scanner.next();
					System.out.println("普通字符串:" + string);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			scanner.close();
		}
	}
	
	// 从键盘读取字符串并在控制太打印输出
	@Test
	public void test2() throws IOException {
		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
		String line = bufferedReader.readLine();
		while (line != null) {
			System.out.println(line);
			line = bufferedReader.readLine();
		}
		bufferedReader.close(); // 键盘流一旦关闭,就无法再使用
	}
	
	@Test
	public void work1() {
		String path = "c:/MyWork";
		File file = new File(path);
		deleteFile(file);
	}
	
	// 删除文件夹及其子目录及子文件夹
	public void deleteFile(File file) {
		if (file.isFile()) {
			file.delete();
		} else {
			File[] childFiles = file.listFiles();
			for (int j = 0; j < childFiles.length; j++) {
				deleteFile(childFiles[j]);
			}
			file.delete();
			System.out.println(file + " 目录删除成功!");
		}
	}
}


你可能感兴趣的:(java,文件复制,IO流,文件删除)