Java中的输入流

 
  
package input;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

public class InPutTest {
	public static void main(String[] args){
		File file = new File("C:\\Users\\Administrator\\Desktop\\a.txt");
//		lineReader(file);
//		characterReader(file);
		byteReader(file);
	}
	/*
	 * 按行读取
	 */
	public static void lineReader(File file){
		BufferedReader bufferedReader = null;
		String temp = "";
		try {
			bufferedReader = new BufferedReader(new FileReader(file));
			while((temp = bufferedReader.readLine()) != null){
				System.out.println(temp);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}catch (IOException e) {
			e.printStackTrace();
		}finally{
			if (bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	/*
	 * 按字符读取
	 */
	public static void characterReader(File file){
		Reader reader = null;
		int temp = 0;
		try {
			reader = new InputStreamReader(new FileInputStream(file));
			while((temp = reader.read()) != -1){
				System.out.print(String.valueOf((char)temp));
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}catch (IOException e) {
			e.printStackTrace();
		}finally{
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	/*
	 * 按字节读取
	 */
	public static void byteReader(File file){
		InputStream inputStream = null;
		byte[] bytes = new byte[1024];
		int temp = 0;
		try {
			inputStream = new FileInputStream(file);
			while((temp = inputStream.read(bytes)) != -1){
				System.out.println(new String(bytes, 0, temp));
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}catch (IOException e) {
			e.printStackTrace();
		}finally{
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

你可能感兴趣的:(Java中的输入流)