[Java]-IO操作标准步骤

  • IO操作标准步骤
  • 1、创建源
  • 2、选择流
  • 3、操作
  • 4、释放资源

在工程文件下建立abc.txt,内容如下

hello you are zhazong

IOTest.java内容如下

package cn.zhazong710.io;

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

/* 
 * IO操作标准步骤
 * 1、创建源
 * 2、选择流
 * 3、操作
 * 4、释放资源
 * 
 * */

public class IOTest {
	public static void main(String[] args)  {
		//1、创建源
		File src = new File("abc.txt");  
		//2、选择流
		InputStream is = null;
		try { 
			is = new FileInputStream(src); 
			//3、操作(分段读取)
			byte[] flush = new byte[1024*10]; //缓冲容器
			int len = -1; //接收长度
			while((len=is.read(flush))!=-1) {
				//字节数组-->字符串(解码)
				String str = new String(flush,0,len);
				System.out.println(str);
			}
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			//4、释放资源
			try {
				if(null!=is) {
					is.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}	
		}
		
	}
}

运行结果如下:

hello you are zhazong

闸总710

感谢观看闸总博客,本博客为个人学习交流使用
订阅
提醒
guest

0 评论
内联反馈
查看所有评论