JAVA学习-----IO数据流
***
一.输入
1.创建源
	File src=new File("test.txt");

2.选择流

InputStream is=null;
	try {
		is=new FileInputStream(src);

3.操作(读取)
未分段:

int temp;
		while((temp=is.read())!=-1) {
			System.out.println((char)temp);
		}

分段:

byte[] flush=new byte[1024];//缓冲容器
		int len=-1;//接收长度
		while((len=is.read(flush))!=-1) {
			//字符数组->字符串(解码)
			String str=new String(flush,0,len);
			System.out.println(str);
		}

4.释放资源(finally)

	try {
			if(null!=is) {
			is.close();
			}

其他,设置相应try和catch。
注:上面换成reader效果更好,只需将is换成reader,此时若有中文输入内容,缓冲容器大小不受限制。


二.输出
过程与输入类似。 1.创建源
		File dest=new File("dest.txt");

2.选择流

OutputStream os=null;
	try {
		os=new FileOutputStream(dest,false);

3.操作(写出内容)

String msg="IO is not easy\r\n";
		byte[] datas=msg.getBytes();
		os.write(datas, 0, datas.length);

4.释放资源(finally)

try {
			if(null!=os) {
			os.close();
			}

注:上面换成writer效果更好,只需将os换成writer。(byte改成char)


三.复制
将输入和输出结合即可,最好封装起来。
public static void copy(String srcPath,String destPath) 

注意:释放资源,分别关闭,先打开的后关闭。


输入和输出时,若加缓冲流,可使时间变短很多。
方法:

try (InputStream is=new BufferedInputStream(new FileInputStream(src));
				OutputStream os=new BufferedOutputStream(new FileOutputStream(dest));){
posted on 2018-09-29 16:31  CGJ_Coco  阅读(107)  评论(0编辑  收藏  举报