java_day25

目标:java Web开发

“游戏次数”实例:
写程序实现猜数字小游戏,只能试玩3次。如果还想玩,提示:试玩已经结束,想玩请充值(www.cnblogs.com)

流的定义:数据的传输
基本IO流:InputStream,OutputStream,Reader,Writer。这4种都是抽象类,不能构建对象,也就是没用

有用的:
  文件输入输出流:FileInputStream,FileOutputStream。可以把一个任意格式的文件从一个位置复制到另一个位置。比如,“字节流复制图片”
  字节缓冲流:BufferedInputStream,BufferedOutputStream。在文件输入输出流上提供了缓冲区,大大提高了传输字节的效率。比如,“字节流复制视频”
  转换流:InputStreamReader,OutputStreamWriter
  ...丫的还没写完qwq

“字节流复制图片”
下面这段代码的效果就相当于你在E盘下用鼠标"haha.jpg"复制到你的Eclipse工作目录下的主文件夹里的src文件夹下
没啥大用处,用来装装逼还可以。

package demo.temp;

import java.io.*;

public class cpoyJpg{
	public static void main(String[] args) throws IOException {
		FileInputStream fis=new FileInputStream("E:\\haha.jpg");
		FileOutputStream fos=new FileOutputStream("src\\haha.jpg");
		byte[] bytes=new byte[1024];
		int len;
		while((len=fis.read(bytes))!=-1) {
			fos.write(bytes,0,len);
		}
		fis.close();
		fos.close();
	}
}

“字节流复制视频”

package demo.temp;

import java.io.*;

public class cpoyMp4{
	public static void main(String[] args) throws IOException {
		long start=System.currentTimeMillis();
//		
//		BufferedInputStream bis=new BufferedInputStream(new FileInputStream("F:\\videos\\1.mp4"));//文件大小:43MB
//		BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream("src\\1.mp4"));
//		byte[] bytes=new byte[1024];
//		int len;
//		while((len=bis.read(bytes))!=-1) {
//			bos.write(bytes,0,len);
//		}
//		bis.close();
//		bos.close();//输出:耗时59毫秒
		
		FileInputStream fis=new FileInputStream("F:\\videos\\1.mp4");
		FileOutputStream fos=new FileOutputStream("src\\1.mp4");
		byte[] bytes=new byte[1024];
		int len;
		while((len=fis.read(bytes))!=-1) {
			fos.write(bytes,0,len);
		}
		fis.close();
		fos.close();//输出:耗时366毫秒
		
		long end=System.currentTimeMillis();
		System.out.println("耗时"+(end-start)+"毫秒");
	}
}

“遍历目录”实例:
要求遍历“D:\codes\java_codes\Demo”下的所有子目录

package demo.temp;

import java.io.*;

public class GetFilePath {
	public static void main(String[] args) {
		File file=new File("D:\\codes\\java_codes\\Demo");
		getAllFilePath(file);
	}
	public static void getAllFilePath(File srcFile) {
		File[] fileArray=srcFile.listFiles();
		if(fileArray!=null) {
			for(File file : fileArray) {
				if(file.isDirectory()) {
					getAllFilePath(file);
				}
				else {
					System.out.println(file.getAbsolutePath());
				}
			}
		}
	}
}

效果:

posted @ 2021-08-04 21:58  zhuangzhongxu  阅读(42)  评论(0)    收藏  举报