輸入流&輸出流經典案例

1.複製單機目錄

package cn.itcast.test;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
/**
 * 複製單機目錄
 * @author Administrator
 *
 */
public class CopyFolder {
	public static void main(String[] args) throws Exception {
		//1.封裝數據源
		File srcFolder=new File("I:\\demo");
		//2.目的地
		File destFolder=new File("I:\\test");
		if(!destFolder.exists()){
			destFolder.mkdirs();
		}
		//3.獲取目錄下的所有文件
		File[] files = srcFolder.listFiles();
		for(File file:files){
			System.out.println(file);
			String name = file.getName();//獲取文件的名字
			File newFile=new  File(destFolder,name);
			Copy(file,newFile);
		}
	}

	private static void Copy(File file, File newFile) throws Exception {
		BufferedInputStream in=new BufferedInputStream(new FileInputStream(file));
		BufferedOutputStream out=new BufferedOutputStream(new FileOutputStream(newFile));
		byte bs[]=new byte[1024];
		int len=0;
		while((len=in.read(bs))!=-1){
			out.write(bs, 0, len);
		}
		
	}
}
2.複製多級目錄

package cn.itcast_05;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/*
 * 需求:複製多極文件夾
 * 
 * 數據源:E:\JavaSE\day21\code\demos
 * 目的地:E:\\
 * 
 * 分析:
 * 		A:封裝數據源File
 * 		B:封裝目的地File
 * 		C:判斷該File是文件夾還是文件
 * 			a:是文件夾
 * 				就在目的地目錄下創建該文件夾
 * 				獲取該File對象下的所有文件或者文件夾File對象
 * 				遍歷得到每一個File對象
 * 				回到C
 * 			b:是文件
 * 				就複製(字節流)
 */
public class CopyFoldersDemo {
	public static void main(String[] args) throws IOException {
		// 封裝數據源File
		File srcFile = new File("E:\\JavaSE\\day21\\code\\demos");
		// 封裝目的地File
		File destFile = new File("E:\\");

		// 複製文件夾的功能
		copyFolder(srcFile, destFile);
	}

	private static void copyFolder(File srcFile, File destFile)
			throws IOException {
		// 判斷該File是文件夾還是文件
		if (srcFile.isDirectory()) {
			// 文件夾
			File newFolder = new File(destFile, srcFile.getName());
			newFolder.mkdir();

			// 獲取該File對象下的所有文件或者文件夾File對象
			File[] fileArray = srcFile.listFiles();
			for (File file : fileArray) {
				copyFolder(file, newFolder);
			}
		} else {
			// 文件
			File newFile = new File(destFile, srcFile.getName());
			copyFile(srcFile, newFile);
		}
	}

	private static void copyFile(File srcFile, File newFile) throws IOException {
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
				srcFile));
		BufferedOutputStream bos = new BufferedOutputStream(
				new FileOutputStream(newFile));

		byte[] bys = new byte[1024];
		int len = 0;
		while ((len = bis.read(bys)) != -1) {
			bos.write(bys, 0, len);
		}

		bos.close();
		bis.close();
	}
}
3.鍵盤錄入5個學生信息(姓名,語文成績,數學成績,英語成績),按照總分從高到低存入文本文件

Student

package cn.itcast_06;

public class Student {
	// 姓名
	private String name;
	// 語文成績
	private int chinese;
	// 數學成績
	private int math;
	// 英語成績
	private int english;

	//省略get set

	public int getSum() {
		return this.chinese + this.math + this.english;
	}
}
StudentDemo

package cn.itcast_06;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Comparator;
import java.util.Scanner;
import java.util.TreeSet;

/*
 * 鍵盤錄入5個學生信息(姓名,語文成績,數學成績,英語成績),按照總分從高到低存入文本文件
 * 
 * 分析:
 * 		A:創建學生類
 * 		B:創建集合對象
 * 			TreeSet<Student>
 * 		C:鍵盤錄入學生信息存儲到集合
 * 		D:遍歷集合,把數據寫到文本文件
 */
public class StudentDemo {
	public static void main(String[] args) throws IOException {
		// 創建集合對象
		TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>() {
			@Override
			public int compare(Student s1, Student s2) {
				int num = s2.getSum() - s1.getSum();
				int num2 = num == 0 ? s1.getChinese() - s2.getChinese() : num;
				int num3 = num2 == 0 ? s1.getMath() - s2.getMath() : num2;
				int num4 = num3 == 0 ? s1.getEnglish() - s2.getEnglish() : num3;
				int num5 = num4 == 0 ? s1.getName().compareTo(s2.getName())
						: num4;
				return num5;
			}
		});

		// 鍵盤錄入學生信息存儲到集合
		for (int x = 1; x <= 5; x++) {
			Scanner sc = new Scanner(System.in);
			System.out.println("請錄入第" + x + "個的學習信息");
			System.out.println("姓名:");
			String name = sc.nextLine();
			System.out.println("語文成績:");
			int chinese = sc.nextInt();
			System.out.println("數學成績:");
			int math = sc.nextInt();
			System.out.println("英語成績:");
			int english = sc.nextInt();

			// 創建學生對象
			Student s = new Student();
			s.setName(name);
			s.setChinese(chinese);
			s.setMath(math);
			s.setEnglish(english);

			// 把學生信息添加到集合
			ts.add(s);
		}

		// 遍歷集合,把數據寫到文本文件
		BufferedWriter bw = new BufferedWriter(new FileWriter("students.txt"));
		bw.write("學生信息如下:");
		bw.newLine();
		bw.flush();
		bw.write("姓名,語文成績,數學成績,英語成績");
		bw.newLine();
		bw.flush();
		for (Student s : ts) {
			StringBuilder sb = new StringBuilder();
			sb.append(s.getName()).append(",").append(s.getChinese())
					.append(",").append(s.getMath()).append(",")
					.append(s.getEnglish());
			bw.write(sb.toString());
			bw.newLine();
			bw.flush();
		}
		// 釋放資源
		bw.close();
		System.out.println("學習信息存儲完畢");
	}
}
4.已知s.txt文件中有這樣的一個字符串:“hcexfgijkamdnoqrzstuvwybpl” 請編寫程序讀取數據內容,把數據排序後寫入ss.txt中。

package cn.itcast_07;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;

/*
 * 已知s.txt文件中有這樣的一個字符串:“hcexfgijkamdnoqrzstuvwybpl”
 * 請編寫程序讀取數據內容,把數據排序後寫入ss.txt中。
 * 
 * 分析:
 * 		A:把s.txt這個文件給做出來
 * 		B:讀取該文件的內容,存儲到一個字符串中
 * 		C:把字符串轉換爲字符數組
 * 		D:對字符數組進行排序
 * 		E:把排序後的字符數組轉換爲字符串
 * 		F:把字符串再次寫入ss.txt中
 */
public class StringDemo {
	public static void main(String[] args) throws IOException {
		// 讀取該文件的內容,存儲到一個字符串中
		BufferedReader br = new BufferedReader(new FileReader("s.txt"));
		String line = br.readLine();
		br.close();

		// 把字符串轉換爲字符數組
		char[] chs = line.toCharArray();

		// 對字符數組進行排序
		Arrays.sort(chs);

		// 把排序後的字符數組轉換爲字符串
		String s = new String(chs);

		// 把字符串再次寫入ss.txt中
		BufferedWriter bw = new BufferedWriter(new FileWriter("ss.txt"));
		bw.write(s);
		bw.newLine();
		bw.flush();

		bw.close();
	}
}
5.自定義自己的MyBufferedReader實現readLine()

package cn.itcast_08;

import java.io.IOException;
import java.io.Reader;

/*
 * 用Reader模擬BufferedReader的readLine()功能
 * 
 * readLine():一次讀取一行,根據換行符判斷是否結束,只返回內容,不返回換行符
 */
public class MyBufferedReader {
	private Reader r;

	public MyBufferedReader(Reader r) {
		this.r = r;
	}

	/*
	 * 思考:寫一個方法,返回值是一個字符串。
	 */
	public String readLine() throws IOException {
		/*
		 * 我要返回一個字符串,我該怎麼辦呢? 我們必須去看看r對象能夠讀取什麼東西呢? 兩個讀取方法,一次讀取一個字符或者一次讀取一個字符數組
		 * 那麼,我們要返回一個字符串,用哪個方法比較好呢? 我們很容易想到字符數組比較好,但是問題來了,就是這個數組的長度是多長呢?
		 * 根本就沒有辦法定義數組的長度,你定義多長都不合適。 所以,只能選擇一次讀取一個字符。
		 * 但是呢,這種方式的時候,我們再讀取下一個字符的時候,上一個字符就丟失了 所以,我們又應該定義一個臨時存儲空間把讀取過的字符給存儲起來。
		 * 這個用誰比較和是呢?數組,集合,字符串緩衝區三個可供選擇。
		 * 經過簡單的分析,最終選擇使用字符串緩衝區對象。並且使用的是StringBuilder
		 */
		StringBuilder sb = new StringBuilder();

		// 做這個讀取最麻煩的是判斷結束,但是在結束之前應該是一直讀取,直到-1
		
		
		/*
		hello
		world
		java	
		
		104101108108111
		119111114108100
		1069711897
		 */
		
		int ch = 0;
		while ((ch = r.read()) != -1) { //104,101,108,108,111
			if (ch == '\r') {
				continue;
			}

			if (ch == '\n') {
				return sb.toString(); //hello
			} else {
				sb.append((char)ch); //hello
			}
		}

		// 爲了防止數據丟失,判斷sb的長度不能大於0
		if (sb.length() > 0) {
			return sb.toString();
		}

		return null;
	}

	/*
	 * 先寫一個關閉方法
	 */
	public void close() throws IOException {
		this.r.close();
	}
}

package cn.itcast_08;

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

/*
 * 測試MyBufferedReader的時候,你就把它當作BufferedReader一樣的使用
 */
public class MyBufferedReaderDemo {
	public static void main(String[] args) throws IOException {
		MyBufferedReader mbr = new MyBufferedReader(new FileReader("my.txt"));

		String line = null;
		while ((line = mbr.readLine()) != null) {
			System.out.println(line);
		}

		mbr.close();

		// System.out.println('\r' + 0); // 13
		// System.out.println('\n' + 0);// 10
	}
}







發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章