雾山的Java学习笔记---I/O(三)(处理流)

处理流是I/O中非常重要的方式,顾名思义就是对输入输出流进行处理,起方式多种多样,不过本质是一样的。

下面就举几个字符输入处理流的例子:

(1):BufferedInputStream/BufferedOutputStream

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

public class BufferStreamTest {
	public static void main(String[] args) {
		int b = 0;
		try {
			BufferedInputStream bis = new BufferedInputStream(
					new FileInputStream("D:\\快盘\\java\\src\\mashibinSE08\\BufferStreamTest.java"));
			BufferedOutputStream bos = new BufferedOutputStream(
					new FileOutputStream("C:\\Users\\Administrator\\Desktop\\test.txt"));
			
		    while((b = bis.read()) != -1){
		    	System.out.print((char)b);
		    	bos.write(b);
		    }
		    bis.close();
		    bos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			System.out.println("文件没找到");
			System.exit(-1);
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("文件读取错误");
			System.exit(-1);
		}
		
	}
}


(2):BufferedReader/BufferedWriter

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 ReadLineTest {
	public static void main(String[] args) {
		String str = null;
		try {
			BufferedReader br = new BufferedReader(
					new FileReader("D:\\快盘\\java\\src\\mashibinSE08\\ReadLineTest.java"));
			
			BufferedWriter bw = new BufferedWriter(
						new	FileWriter("C:\\Users\\Administrator\\Desktop\\test.txt"));
			
			while((str = br.readLine()) != null){
				System.out.println(str);
				bw.write(str);
			}
			br.close();
			bw.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			System.out.println("文件没找到");
			System.exit(-1);
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("文件读取错误");
			System.exit(-1);
		}
	}
}


(3):按行读取

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

//输入字符处理流
public class BufferReaderTest {
	public static void main(String[] agrs){
		FileReader fileReader = null;
		//定义一个BufferedReader的引用
		BufferedReader bufferedReader = null;
		try {
			fileReader = new FileReader("d:/input.txt");
			bufferedReader = new BufferedReader(fileReader);
			String line = null;
			while(true){
			   //读取输入流的每一行数据
			   line =bufferedReader.readLine();
			   if(line == null){
				   break;
			   }
			   System.out.println(line);
			}
		} catch (FileNotFoundException e) {
			System.out.println("文件未找到");
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("发生IO异常");
		}
	}

}


你可能感兴趣的:(Java,io,java)