java之IO流学习

操作步骤

  1. 创建源
  2. 选择流
  3. 操作
  4. 释放资源
package 第8章io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

/**
 * 操作步骤
 * 1.创建源
 * 2.选择流
 * 3.操作
 * 4.释放资源
 * @author thinkpad
 *
 */
public class IOTest01 {

	public static void main(String[] args) {
		//1.创建源
		File src = new File("D:abc.txt");
		//2.选择流
		try {
			InputStream is = new FileInputStream(src);
			//2.操作流(读取)
			int data1 = is.read();
			int data2 = is.read();
			int data3 = is.read();
			int data4 = is.read();
			System.out.println((char)data1);
			System.out.println((char)data2);
			System.out.println((char)data3);
			System.out.println(data4);
			//4.释放资源
			is.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		

	}

}

如果读取不到,则返回-1
在这里插入图片描述
用循环读取数据

public class IOTest02 {

	public static void main(String[] args) {
		//1、创建源
		File src = new File("abc.txt");
		//2、选择流
		InputStream  is =null;
		try {
			is =new FileInputStream(src);
			//3、操作 (读取)
			int temp ;
			while((temp=is.read())!=-1) {
				System.out.println((char)temp);
			}		
		
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			//4、释放资源
			try {
				if(null!=is) {
					is.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}

喜欢我的可以关注我,我们可以一起交流学习

微信公众号:

让我爱上它Computer

qq群:473989408

发布了68 篇原创文章 · 获赞 15 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_42913025/article/details/102465922