读、写(记)(2015年10月14日)

时间:2020-12-25 18:53:14

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;


public class filereadtest01 {
	public static void main(String[] args) {
		testBw();
		testBr();
	}
	
	public static void testBr() {
		try {
			BufferedReader br = new BufferedReader(new FileReader(new File("c:/testbwbr.txt")));
			String str;
			while((str =br.readLine())!=null) {
				 System.out.println(str);
			}
			br.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void testBw() {
		BufferedWriter bw = null;
		try {
			bw = new BufferedWriter(new FileWriter(new File("c:/testbwbr.txt")));
			Scanner sc = new Scanner(System.in);
			System.out.println("请输入第一行:");
			String str1 = sc.nextLine();
			System.out.println("请输入第二行:");
			String str2 = sc.nextLine();
			bw.write(str1);
			bw.newLine();
			bw.write(str2);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				bw.flush();
				bw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}	

熟练掌握!