天天看點

IO流位元組字元流練習題

A:複制文本檔案 5種方式(掌握)

Test:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class Test {
	public static void main(String[] args) throws IOException {
		String yuanStr="002.txt";
		String xinStr="003.txt";
		
//		Filech(yuanStr, xinStr);
//		Filechs(yuanStr, xinStr);
//		Bufferedch(yuanStr, xinStr);
//		Bufferedchs(yuanStr, xinStr);
		BufferedLine(yuanStr, xinStr);
		
	}
	//Buffered類一次讀寫一行
	public static void BufferedLine(String yuanStr,String xinStr) throws IOException{
		BufferedReader br=new BufferedReader(new FileReader(yuanStr));
		BufferedWriter bw=new BufferedWriter(new FileWriter(xinStr));
		String s=null;
		while((s=br.readLine())!=null){
			bw.write(s);
			bw.newLine();
		}
		br.close();
		bw.close();
	}
	
	//Buffered類一次讀寫一個字元數組
	public static void Bufferedchs(String yuanStr,String xinStr) throws IOException{
		BufferedReader br=new BufferedReader(new FileReader(yuanStr));
		BufferedWriter bw=new BufferedWriter(new FileWriter(xinStr));
		char[] chs=new char[1024];
		int len=0;
		while((len=br.read(chs))!=-1){
			bw.write(chs, 0, len);
		}
		br.close();
		bw.close();
	}
	
	//Buffered類一次讀寫一個字元
	public static void Bufferedch(String yuanStr,String xinStr) throws IOException{
		BufferedReader br=new BufferedReader(new FileReader(yuanStr));
		BufferedWriter bw=new BufferedWriter(new FileWriter(xinStr));
		int ch=0;
		while((ch=br.read())!=-1){
			bw.write(ch);
		}
		br.close();
		bw.close();
		
	}
	
	//File類一次讀寫一個字元數組
	public static void Filechs(String yuanStr, String xinStr) throws IOException{
		FileReader fr=new FileReader(yuanStr);
		FileWriter fw=new FileWriter(xinStr);
		
		char[] chs=new char[1024];
		int len=0;
		while((len=fr.read(chs))!=-1){
			fw.write(chs,0,len);
		}
		fr.close();
		fw.close();
	}
	
	//File類,一次讀取寫入一個字元
	public static void Filech(String yuanStr, String xinStr) throws IOException{
		FileReader fr=new FileReader(yuanStr);
		FileWriter fw=new FileWriter(xinStr);
		int ch=0;
		while((ch=fr.read())!=-1){
			fw.write(ch);
		}
		fr.close();
		fw.close();
		
	}
}      

B:複制圖檔(二進制流資料) 4種方式(掌握)

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

public class CopyPhoto {

	public static void main(String[] args) throws IOException {
		String yuanStr="1.jpg";
		String xinStr="2.jpg";
		//Fileb(yuanStr, xinStr);
		//Filebs(yuanStr, xinStr);
		//Bufferedb(yuanStr, xinStr);
		Bufferedbs(yuanStr, xinStr);
		
	}
	//Buffer位元組數組複制圖檔
	public static void Bufferedbs(String yuanStr,String xinStr) throws IOException{
		BufferedInputStream bis=new BufferedInputStream(new FileInputStream(yuanStr));
		BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(xinStr));
		byte[] bs=new byte[1024];
		int len=0;
		while((len=bis.read(bs))!=-1){
			bos.write(bs,0,len);
		}
		bis.close();
		bos.close();
	}
	
	//Buffer位元組複制圖檔
	public static void Bufferedb(String yuanStr,String xinStr) throws IOException{
		BufferedInputStream bis=new BufferedInputStream(new FileInputStream(yuanStr));
		BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(xinStr));
		int b=0;
		while((b=bis.read())!=-1){
			bos.write(b);
		}
		bis.close();
		bos.close();
	}
	
	//位元組數組複制圖檔
	public static void Filebs(String yuanStr,String xinStr) throws IOException{
		FileInputStream fis=new FileInputStream(yuanStr);
		FileOutputStream fos=new FileOutputStream(xinStr);
		byte[] bs=new byte[1024];
		int len=0;
		while((len=fis.read(bs))!=-1){
			fos.write(bs, 0, len);
		}
		fis.close();
		fos.close();
	}
	
	//單位元組流複制圖檔
	public static void Fileb(String yuanStr,String xinStr) throws IOException{
		FileOutputStream fos=new FileOutputStream(xinStr);
		FileInputStream fis=new FileInputStream(yuanStr);
		int b=0;
		while((b=fis.read())!=-1){
			fos.write(b);
		}
		fis.close();
		fos.close();
	}
}      

C:把集合中的資料存儲到文本檔案

Demo:

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

/*
 * 需求:把ArrayList集合中的字元串資料存儲到文本檔案
 * 
 * 分析:
 * 		通過題目的意思我們可以知道如下的一些内容,
 * 			ArrayList集合裡存儲的是字元串。
 * 			周遊ArrayList集合,把資料擷取到。
 * 			然後存儲到文本檔案中。
 * 			文本檔案說明使用字元流。
 * 
 * 資料源:
 * 		ArrayList<String> -- 周遊得到每一個字元串資料
 * 目的地:
 * 		a.txt -- FileWriter -- BufferedWriter
 */
public class ArrayListToFileDemo {
	public static void main(String[] args) throws IOException {
		// 封裝資料與(建立集合對象)
		ArrayList<String> array = new ArrayList<String>();
		array.add("hello");
		array.add("world");
		array.add("java");

		// 封裝目的地
		BufferedWriter bw = new BufferedWriter(new FileWriter("a.txt"));

		// 周遊集合
		for (String s : array) {
			// 寫資料
			bw.write(s);
			bw.newLine();
			bw.flush();
		}

		// 釋放資源
		bw.close();
	}
}      
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

public class ListToFile {

	public static void main(String[] args) throws IOException {
		ArrayList<String> list=new ArrayList<>();
		list.add("Hello");
		list.add("World");
		list.add("Java");
		list.add("Wade");
		list.add("Tim");
		
		ArrayList<Student> list2=new ArrayList<>();
		list2.add(new Student("雷阿倫",37));
		list2.add(new Student("韋德",35));
		list2.add(new Student("鄧肯",38));
		list2.add(new Student("漢密爾頓",39));
		list2.add(new Student("保羅",31));
		
		//字元串類型測試
		BufferedWriter bw=new BufferedWriter(new FileWriter("004.txt"));
		for(String s:list){
			bw.write(s);
		}
		bw.close();
		
		//自定義類型測試
		BufferedWriter bw2=new BufferedWriter(new FileWriter("005.txt"));
		for(Student s:list2){
			bw2.write(s.getName()+"\t"+s.getAge()+"\r\n");
		}
		bw2.close();
	}
}      

D:把文本檔案中的資料讀取到集合并周遊集合

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

/*
 * 需求:從文本檔案中讀取資料(每一行為一個字元串資料)到集合中,并周遊集合
 * 
 * 分析:
 * 		通過題目的意思我們可以知道如下的一些内容,
 * 			資料源是一個文本檔案。
 * 			目的地是一個集合。
 * 			而且元素是字元串。
 * 
 * 資料源:
 * 		b.txt -- FileReader -- BufferedReader
 * 目的地:
 * 		ArrayList<String>
 */
public class FileToArrayListDemo {
	public static void main(String[] args) throws IOException {
		// 封裝資料源
		BufferedReader br = new BufferedReader(new FileReader("b.txt"));
		// 封裝目的地(建立集合對象)
		ArrayList<String> array = new ArrayList<String>();

		// 讀取資料存儲到集合中
		String line = null;
		while ((line = br.readLine()) != null) {
			array.add(line);
		}

		// 釋放資源
		br.close();

		// 周遊集合
		for (String s : array) {
			System.out.println(s);
		}
	}
}      
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

public class FileToList {

	public static void main(String[] args) throws IOException {
		//讀取文本檔案到集合并周遊
		BufferedReader br = new BufferedReader(new FileReader("005.txt"));
		ArrayList<String> list = new ArrayList<>();
		//逐行寫入集合
		String s = null;
		while ((s = br.readLine()) != null) {
			list.add(s);
		}
		br.close();
		//周遊集合
		for (String str : list) {
			System.out.println(str);
		}
	}
}      

文本檔案中有若幹名字,随機擷取其中一個:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;

/*
 * 需求:我有一個文本檔案中存儲了幾個名稱,請大家寫一個程式實作随機擷取一個人的名字。
 * 
 * 分析:
 * 		A:把文本檔案中的資料存儲到集合中
 * 		B:随機産生一個索引
 * 		C:根據該索引擷取一個值
 */
public class GetName {
	public static void main(String[] args) throws IOException {
		// 把文本檔案中的資料存儲到集合中
		BufferedReader br = new BufferedReader(new FileReader("b.txt"));
		ArrayList<String> array = new ArrayList<String>();
		String line = null;
		while ((line = br.readLine()) != null) {
			array.add(line);
		}
		br.close();

		// 随機産生一個索引
		Random r = new Random();
		int index = r.nextInt(array.size());

		// 根據該索引擷取一個值
		String name = array.get(index);
		System.out.println("該幸運者是:" + name);
	}
}      
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Random;
import java.util.Set;

public class getName {

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new FileReader("name.txt"));
		HashMap<Integer, String> hm = new HashMap<>();
		String line = null;
		int num = 0;
		while ((line = br.readLine()) != null) {
			hm.put(num, line);
			num++;
		}
		br.close();
		
		// 周遊鍵值對集合
		// Set<Integer> set = hm.keySet();
		// for (Integer in : set) {
		// System.out.println(in + "\t" + hm.get(in));
		// }
		// System.out.println("++++++++++++++++++++++");

		// 建立随機數對象
		Random r = new Random();
		for (int i = 0; i < 20; i++) {
			// 得到集合長度範圍内的随機數,輸出對應的值
			System.out.println(hm.get(r.nextInt(hm.size())));
		}
	}

}      

E:複制單級檔案夾

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:\\demo
 * 目的地:e:\\test
 * 
 * 分析:
 * 		A:封裝目錄
 * 		B:擷取該目錄下的所有文本的File數組
 * 		C:周遊該File數組,得到每一個File對象
 * 		D:把該File進行複制
 */
public class CopyFolderDemo {
	public static void main(String[] args) throws IOException {
		// 封裝目錄
		File srcFolder = new File("e:\\demo");
		// 封裝目的地
		File destFolder = new File("e:\\test");
		// 如果目的地檔案夾不存在,就建立
		if (!destFolder.exists()) {
			destFolder.mkdir();
		}

		// 擷取該目錄下的所有文本的File數組
		File[] fileArray = srcFolder.listFiles();

		// 周遊該File數組,得到每一個File對象
		for (File file : fileArray) {
			// System.out.println(file);
			// 資料源:e:\\demo\\e.mp3
			// 目的地:e:\\test\\e.mp3
			String name = file.getName(); // e.mp3
			File newFile = new File(destFolder, name); // e:\\test\\e.mp3

			copyFile(file, newFile);
		}
	}

	private static void copyFile(File file, File newFile) throws IOException {
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
				file));
		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();
	}
}      

F:複制單級檔案夾中指定的檔案并修改名稱

回顧一下批量修改名稱

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

/*
 * 需求:複制指定目錄下的指定檔案,并修改字尾名。
 * 指定的檔案是:.java檔案。
 * 指定的字尾名是:.jad
 * 指定的目錄是:jad
 * 
 * 資料源:e:\\java\\A.java
 * 目的地:e:\\jad\\A.jad
 * 
 * 分析:
 * 		A:封裝目錄
 * 		B:擷取該目錄下的java檔案的File數組
 * 		C:周遊該File數組,得到每一個File對象
 * 		D:把該File進行複制
 * 		E:在目的地目錄下改名
 */
public class CopyFolderDemo {
	public static void main(String[] args) throws IOException {
		// 封裝目錄
		File srcFolder = new File("e:\\java");
		// 封裝目的地
		File destFolder = new File("e:\\jad");
		// 如果目的地目錄不存在,就建立
		if (!destFolder.exists()) {
			destFolder.mkdir();
		}

		// 擷取該目錄下的java檔案的File數組
		File[] fileArray = srcFolder.listFiles(new FilenameFilter() {
			@Override
			public boolean accept(File dir, String name) {
				return new File(dir, name).isFile() && name.endsWith(".java");
			}
		});

		// 周遊該File數組,得到每一個File對象
		for (File file : fileArray) {
			// System.out.println(file);
			// 資料源:e:\java\DataTypeDemo.java
			// 目的地:e:\\jad\DataTypeDemo.java
			String name = file.getName();
			File newFile = new File(destFolder, name);
			copyFile(file, newFile);
		}

		// 在目的地目錄下改名
		File[] destFileArray = destFolder.listFiles();
		for (File destFile : destFileArray) {
			// System.out.println(destFile);
			// e:\jad\DataTypeDemo.java
			// e:\\jad\\DataTypeDemo.jad
			String name =destFile.getName(); //DataTypeDemo.java
			String newName = name.replace(".java", ".jad");//DataTypeDemo.jad
			
			File newFile = new File(destFolder,newName);
			destFile.renameTo(newFile);
		}
	}

	private static void copyFile(File file, File newFile) throws IOException {
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
				file));
		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();
	}
}      

G:複制多級檔案夾

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();
	}
}      

H:鍵盤錄入學生資訊按照總分從高到低存儲到文本檔案

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("學習資訊存儲完畢");
	}
}      

I:把某個檔案中的字元串排序後輸出到另一個文本檔案中

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();
	}
}      

J:用Reader模拟BufferedReader的特有功能

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();
	}
}      

Demo2:

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
	}
}      

K:模拟LineNumberReader的特有功能

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

/*
 * BufferedReader
 * 		|--LineNumberReader
 * 			public int getLineNumber()獲得目前行号。 
 * 			public void setLineNumber(int lineNumber)
 */
public class LineNumberReaderDemo {
	public static void main(String[] args) throws IOException {
		LineNumberReader lnr = new LineNumberReader(new FileReader("my.txt"));

		// 從10開始才比較好
		// lnr.setLineNumber(10);

		// System.out.println(lnr.getLineNumber());
		// System.out.println(lnr.getLineNumber());
		// System.out.println(lnr.getLineNumber());

		String line = null;
		while ((line = lnr.readLine()) != null) {
			System.out.println(lnr.getLineNumber() + ":" + line);
		}

		lnr.close();
	}
}      
import java.io.IOException;
import java.io.Reader;

public class MyLineNumberReader {
	private Reader r;
	private int lineNumber = 0;

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

	public int getLineNumber() {
		// lineNumber++;
		return lineNumber;
	}

	public void setLineNumber(int lineNumber) {
		this.lineNumber = lineNumber;
	}

	public String readLine() throws IOException {
		lineNumber++;

		StringBuilder sb = new StringBuilder();

		int ch = 0;
		while ((ch = r.read()) != -1) {
			if (ch == '\r') {
				continue;
			}

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

		if (sb.length() > 0) {
			return sb.toString();
		}

		return null;
	}

	public void close() throws IOException {
		this.r.close();
	}
}      

Demo3:

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

import cn.itcast_08.MyBufferedReader;

public class MyLineNumberReader2 extends MyBufferedReader {
	private Reader r;

	private int lineNumber = 0;

	public MyLineNumberReader2(Reader r) {
		super(r);
	}

	public int getLineNumber() {
		return lineNumber;
	}

	public void setLineNumber(int lineNumber) {
		this.lineNumber = lineNumber;
	}

	@Override
	public String readLine() throws IOException {
		lineNumber++;
		return super.readLine();
	}
}      
import java.io.FileReader;
import java.io.IOException;

public class MyLineNumberReaderTest {
	public static void main(String[] args) throws IOException {
		// MyLineNumberReader mlnr = new MyLineNumberReader(new FileReader(
		// "my.txt"));

		MyLineNumberReader2 mlnr = new MyLineNumberReader2(new FileReader(
				"my.txt"));

		// mlnr.setLineNumber(10);

		// System.out.println(mlnr.getLineNumber());
		// System.out.println(mlnr.getLineNumber());
		// System.out.println(mlnr.getLineNumber());

		String line = null;
		while ((line = mlnr.readLine()) != null) {
			System.out.println(mlnr.getLineNumber() + ":" + line);
		}

		mlnr.close();
	}
}