java io 流

IO流基础知识

1创建File的三种基本方式

1.1 File(String str);

File f=new File("E:/project/IO_study/1.png");   

1.2 File (String parent,String child)

File f=new File("E:/project/IO_study","1.png");

1.3 File(File parent,String child)

File f=new File(new File("E:/project/IO_study"),"1.png");

2 构建File对象(相对路径与绝对路径)

2.1 代码:

String path="E:/project/IO_study/1.png";
 // 绝对路径
File src=new File("E:/project/IO_study/1.png");
System.out.println("绝对路径为:"+src.getAbsolutePath());
System.out.println("当前项目为:"+System.getProperty("user.dir"));
 // 相对路径
 src=new File("1.png");
 System.out.println(src.getAbsolutePath());
 // 构建一个不存在的文件
 src= new File("aaa/i2.png");
 System.out.println(src.getAbsolutePath());

2.2 代码结果如下:

E:\project\IO_study\1.png
E:\workspace\JAVAIO
E:\workspace\JAVAIO\1.png
E:\workspace\JAVAIO\aaa\i2.png

3 获取File对象名称或者路径

3.1 代码:

File f=new File("E:/project/IO_study/1.png");
System.out.println("名称:"+f.getName());
System.out.println("路径:"+f.getPath());
System.out.println("绝对路径:"+f.getAbsolutePath());
System.out.println("父路径:"+f.getParent());
System.out.println("父对象:"+f.getParentFile().getName());

3.2 代码结果如下

名称:1.png
路径:E:\project\IO_study\1.png
绝对路径:E:\project\IO_study\1.png
父路径:E:\project\IO_study
父对象:IO_study

4 文件状态

4.1 代码

File f=new File("E:/project/IO_study/1.png");
System.out.println("是否存在:"+f.exists());
System.out.println("是否文件:"+f.isFile());
System.out.println("是否目录:"+f.isDirector());

4.2 代码结果如下:

是否存在true
是否文件true
是否文件夹false

5 其他信息

5.1 长度

File f=new File("E:/project/IO_study/1.png");
System.out.println("文件长度:"+f.length());
f=new File("E:/project/IO_study");
System.out.println("目录长度:"+f.length());

5.1 代码结果如下:

文件长度:29553
目录长度:0

5.2 创建/删除文件

File f=new File("E:/project/IO_study/1.png");
Boolean flag=f.createNewFile();
System.out.println("是否创建文件"+flag);
flag=f.delete();
System.out.println("是否删除文件"+flag);

5.2 代码结果如下:

是否创建文件true
是否删除文件true

5.3 名称分隔符 separator

String path="E:\\project\\IO_study\\1.png";
         // 建议
         // 1 /
         path="E:/project/IO_study/1.png";
         System.out.println(path);
         //2 常量拼接
         path="E:"+File.separator+"project"+File.separator+"IO_study"+File.separator+"1.png";
         
         System.out.println(path);

5.3 代码如下

E:/project/IO_study/1.png
E:\project\IO_study\1.png

6 目录信息

// 定义File 对象
File dir = new File("E:/project/IO_study");

6.1 list file 对象下的下一级名称

String[] list = dir.list();
   for (String a : list) {
	  System.out.println(a);
   }

6.2 listFiles file 对象下的所有file对象

File[] listFiles = dir.listFiles();
		for(File a:listFiles) {
			System.out.println(a);
		}

6.3 listRoots file 对象所在系统的所有盘符

File[] listRoots = dir.listRoots();
		for(File a:listRoots) {
			System.out.println(a);
		}

7 创建目录

File dir=new File("E:/project/IO_study/dir/test");

7.1 mkdir :确保上级目录存在

boolean flag=dir.mkdir();

7.2 mkdirs: 上级目录可以不存在

 boolean flag=dir.mkdirs();

8 递归

8.1 用法: 递归头:合适结束自己 递归体:重复调用

public static void main(String[] args) {
     File dir=new File("E:/project/IO_study/dir/test");
     printTen(1);
	}
	public static void printTen(int n) {
		if(n>10) {
			return ;
		}
		System.out.println(n);
		printTen(n+1);
	}

9 递归打印子孙文件

public static void main(String[] args) {
     File src=new File("E:/project");
     printName(src,0);
	}
	public static void printName(File src,int deep) {
		// 控制层次感的
		for(int i=0;i<deep;i++) {
			System.out.print("-");
		}
		System.out.println(src.getName());
		if(null==src||!src.exists()){
			// 递归头
			return ;
		}else if(src.isDirectory()) {
			// 递归体
			for (File s : src.listFiles()) {
				printName(s, deep + 1);
			}
		}
	}

10使用面向对象统计文件夹的大小

public static void main(String[] args) {
		File src = new File("E:/project");
		count(src);
		System.out.println(len);
	}
    private static long len=0;
	public static void count(File src) {
       if(src!=null&&src.exists()) {
    	   if(src.isFile()) {  // 大小
    		   len+=src.length();
    	   }else {// 子孙级
    		   for(File s:src.listFiles()) {
    			   count(s);
    		   }
    	   }
       }
	}

11 统计文件夹的大小


	// 大小
	private long len=0;
	// 文件夹
	private String path;
	// 文件个数
	private int fileSize;
	// 文件夹个数
	private int dirSize;
	// 源
	private File src;

	public DirDemo6(String path) {
		this.path = path;
		this.src = new File(path);
		count(src);
	}

	public static void main(String[] args) {
		DirDemo6 dir = new DirDemo6("E:/project");
		System.out.println(dir.getLen());
		System.out.println(dir.getDirSize());
		System.out.println(dir.getFileSize());
		DirDemo6 dir1 = new DirDemo6("E:/project/IO_study");
		System.out.println(dir1.getLen());
		System.out.println(dir1.getDirSize());
		System.out.println(dir1.getFileSize());
	}
     
	private void count(File src) {
		if (src != null && src.exists()) {
			if (src.isFile()) {
				// 大小
				len += src.length();
				this.fileSize++;
			} else {
				this.dirSize++;
				// 子孙级
				for (File s : src.listFiles()) {
					count(s);
				}
			}
		}
	}

	/**
	 * @return the len
	 */
	public long getLen() {
		return len;
	}

	/**
	 * @param len the len to set
	 */
	public void setLen(long len) {
		this.len = len;
	}

	/**
	 * @return the fileSize
	 */
	public int getFileSize() {
		return fileSize;
	}

	/**
	 * @param fileSize the fileSize to set
	 */
	public void setFileSize(int fileSize) {
		this.fileSize = fileSize;
	}

	/**
	 * @return the dirSize
	 */
	public int getDirSize() {
		return dirSize;
	}

	/**
	 * @param dirSize the dirSize to set
	 */
	public void setDirSize(int dirSize) {
		
	}	

12 编码解码

12.1 字符串–>字节 编码

public static void main(String[] args) throws UnsupportedEncodingException {
      String msg="姓名生命使命";
      // 编码:字节数组
      byte[] datas=msg.getBytes();  // 默认使用工程的字符集
      System.out.println(datas.length);
      
      // 编码其他字符集
      datas=msg.getBytes("UTF-16LE");
      System.out.println(datas.length);
	}

12.2 字节–>字符 解码

public static void main(String[] args) throws UnsupportedEncodingException {
		String msg="姓名生命使命";
		byte[] datas=msg.getBytes();  // 默认使用工程的字符集
		
		// 解码:
		msg=new String(datas,0,datas.length,"gbk");
		System.out.println(msg);
	}

13 理解IO操作流步骤

13.1 创建源

13.2 选择流

13.3 操作

13.4 释放资源

        // 1 创建源
		File src =new File("abc.txt");
		// 2 选择流
		try {
			InputStream is=new FileInputStream(src);
			// 3 操作
			int data1=is.read();
			int data2=is.read();
			int data3=is.read();
			int data4=is.read();  // 返回的不是数据,而是字节码,文件的末尾返回-1
			System.out.println((char)data1);
			System.out.println((char)data2);
			System.out.println((char)data3);
			// 4释放资源
			is.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	

13.5 循环读出流文件的全部内容(一个字节一个字节的读取)

        // 1 创建源
		File src=new File("abc.txt");
		InputStream is=null;
		try {
			// 2 选择流
			 is=new FileInputStream(src);
			int temp;
			while((temp=is.read())!=-1) {
				System.out.println((char)temp);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		finally {
			try {
				if (is != null) {
					is.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	

13.6 使用缓冲容器读取流文件(缓冲器大小读取)

            // 2 选择流
			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);
			}

13.7 FileReader读取流文件(一般用于流中只包含文字的)

		// 1 创建源
		File file = new File("abc.txt");
		Reader reader = null;
		try {
			// 2 选择流
			reader = new FileReader(file);
			// 3 操作流
			char[] flush = new char[1024];
			int len = -1;
			while ((len = reader.read(flush)) != -1) {
				String str = new String(flush, 0, len);
				System.out.println(str);
			}
		} catch (Exception e) {
		} finally {
			try {
				if (reader != null) {
					reader.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	

13.8 FileOutputStream流输出到文件

		// 1 创建源
		File file = new File("b.txt");
		OutputStream os = null;
		try {
			// 2 选择流
			os = new FileOutputStream(file);
			// 3 操作流
			String msg = "今天的你一定会感谢当你努力的你";
			byte[] b = msg.getBytes();
			os.write(b);
			os.flush();
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			try {
				if (os != null) {
					os.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	

13.9 文件字符输出流

		try {
			writer = new FileWriter(dest);
			//3、操作(写出)
			//写法一
//			String msg ="今天的你一定会感谢当你努力的你";
//			char[] datas =msg.toCharArray(); // 字符串-->字符数组
//			writer.write(datas,0,datas.length);
			//写法二
			/*String msg ="IO is so easy\r\n尚学堂欢迎你";
			writer.write(msg);	
			writer.write("add");		
			writer.flush();*/
			
			//写法三
			writer.append("IO is so easy\r\n").append("尚学堂欢迎你");
			writer.flush();
		}catch(FileNotFoundException e) {		
			e.printStackTrace();
		}catch (IOException e) {
			e.printStackTrace();
		}finally{
			//4、释放资源
			try {
				if (null != writer) {
					writer.close();
				} 
			} catch (Exception e) {
			}
		}

13.10 字节数组输入流 ByteArrayOutPutStream

        //1、创建源
 		byte[] src = "talk is cheap show me the code".getBytes();
		//2、选择流
		InputStream  is =null;
		try {
			is =new ByteArrayInputStream(src);
			//3、操作 (分段读取)
			byte[] flush = new byte[5]; //缓冲容器
			int len = -1; //接收长度
			while((len=is.read(flush))!=-1) {
				//字节数组-->字符串 (解码)
				String str = new String(flush,0,len);
				System.out.println(str);
			}		
		
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			//4、释放资源
			try {
				if(null!=is) {
					is.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

13.11 ByteArrayOutputStream

		// 1 创建源
		byte [] dest=null;
		// 2 选择流
		ByteArrayOutputStream bos=null;
		try {
			bos=new ByteArrayOutputStream();
			String msg="show me the code";
			byte [] datas=msg.getBytes(); // 字符串转字节数据
             bos.write(datas, 0, datas.length);
             bos.flush();
             // 获取数据
             dest=bos.toByteArray();
             System.out.println(dest.length+"--->"+new String(dest,0,dest.length));
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (bos != null) {
					bos.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	

13.12 图片读取到字节数组 且 字节数组写出到文件

	public static void main(String[] args) {
		byte[] datas=fileToByteArray("1.png");
		System.out.println(datas.length);
		byteArrayToFile(datas,"2copy.png");
	}
	/**
	 * 1 图片读取到字节数组中
	 *    1 图片到程序 FileInputStreat
	 *    2 程序到字节数组 byteArrayInputStream
	 */
	public static byte[] fileToByteArray(String filePath) {
		// 1创建源
		File file = new File(filePath);
		byte[] dest=null;
		// 2 选择流
		InputStream is=null;
		ByteArrayOutputStream baos=null;
		try {
			is=new FileInputStream(file);
			baos=new ByteArrayOutputStream();
			byte[] flush=new byte[1024*10];
			int len=-1;
			while((len=is.read(flush))!=-1) {
              baos.write(flush, 0, len);
              baos.flush();
			}
			return baos.toByteArray();
		} catch (Exception e) {
		}
		return null;
	}
	/**
	 * 2 字节数组写出到图片
	 *    1 字节数组读取到程序中 bytearrayinputStrem
	 *    2 程序数组写出到文件 FileOutPutStream 
	 */
	public static void byteArrayToFile(byte[] src,String filePath) {
		// 选择目标文件
	    FileOutputStream os=null;
	    ByteArrayInputStream is=null;
	    try {
			os=new FileOutputStream(filePath);
			is=new ByteArrayInputStream(src);
			byte[] flush=new byte[5];
			int len=-1;
			while((len=is.read(flush))!=-1) {
			   os.write(flush, 0, len);
			   os.flush();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	    finally {
	    	if(os!=null){
	    		try {
					os.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	    	}
	    }
	}

13.13 文件输入流和输出流 拷贝文件

	public static void main(String[] args) {
		copy("1.png", "1copy.png");
	}
	public static void copy(String srcPath, String destPath) {

		// 1 创建源
		File src = new File(srcPath); // 源头
		File dest = new File(destPath); // 目的地
		// 2 选择流
		InputStream is = null;
		OutputStream os = null;
		try {
			is = new FileInputStream(src);
			os = new FileOutputStream(dest);
			// 操作流(分段读取)
			byte[] flush = new byte[1024];
			int len = -1;
			while ((len = is.read(flush)) != -1) {
				os.write(flush, 0, len);
			}
			os.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 4 释放资源 分别关闭,先打开的后关闭
			try {
				if (os != null) {
					os.close();
				}
				if (is != null) {
					is.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

13.14 封装释放资源

	public static void main(String[] args) {
       // 文件到文件
		InputStream is=null;
		OutputStream os=null;
		try {
			 is =new FileInputStream("abc.txt");
			 os=new FileOutputStream("abc-copy.txt");
			 copy(is,os);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		// 文件到字节数组
		InputStream is1=null;
		ByteArrayOutputStream os1=null;
		byte[] datas=null;
		try {
			is1=new FileInputStream("1.png");
			os1=new ByteArrayOutputStream();
			copy(is1,os1);
			 datas=os1.toByteArray();
			System.out.println(datas.length);
		} catch (Exception e) {

		}
		// 字节数组到文件
		ByteArrayInputStream is2=null;
		OutputStream os2=null;
		try {
			is2=new ByteArrayInputStream(datas);
			os2=new FileOutputStream("1-copy.png");
			copy(is2,os2);
			
		} catch (Exception e) {
			
		}
	}
	/**
	 * 对接输入输出流
	 * @param is
	 * @param os
	 */
	public static void copy(InputStream is,OutputStream os) {
		try {
			// 操作[分段读取]
			byte[] flush=new byte[1024];
			int len=-1;
			while((len=is.read(flush))!=-1) {
				os.write(flush, 0, len); // 分段写出
			}
			os.flush();
		} catch (Exception e) {

		}finally {
			// 释放资源
			close(is, os);
		}
	}
	/**
	 * 关闭流方法
	 */
	public static void close(InputStream is,OutputStream os) {
		try {
			if(os!=null) {
				os.close();
				os=null;
			}
			if(is!=null) {
				is.close();
				is=null;
			}
		} catch (Exception e2) {
		}
	}
	/**
	 * 释放资源,可以关闭多个流
	 * @param ios
	 */
	public static void close(Closeable...ios) {
		for(Closeable io:ios) {
			try {
				if(io!=null) {
					io.close();
					io=null;
				}
			} catch (Exception e2) {
			}
		}
	}

14 装修类

14.1 装修类的理解(实现放大器对声音的放大功能)

public class DecorateTest01 {
    public static void main(String[] args) {
		Person p=new Person();
		p.say();
		// 装饰
		Amplifier am=new Amplifier(p);
		am.say();
	}
}
interface Say{
	void say();
}
class Person implements Say{
	// 属性
	private int voice=10;
	@Override
	public void say() {
	
	System.out.println("人的声音为"+this.getVoice());	
	}
	/**
	 * @return the voice
	 */
	public int getVoice() {
		return voice;
	}
	/**
	 * @param voice the voice to set
	 */
	public void setVoice(int voice) {
		this.voice = voice;
	}
	
}

class Amplifier implements Say{
	private Person p;
	
	public Amplifier(Person p) {
		this.p=p;
	}

	@Override
	public void say() {
	    System.out.println("人的声音为"+p.getVoice()*100);	
	    System.out.println("噪音。。。");
	}
}

14.2 装修类的组成部分

14.2.1 抽象组件:需要装饰的抽象对象(接口或抽象父类)

14.2.2 具体组件:需要装饰的对象

14.2.3 抽象装饰类:包含了对抽象组件的引用以及装饰着共有的方法

14.2.4 具体装饰类:被装饰的对象

public class DecorateTest02 {
	public static void main(String[] args) {
		Drink coffee =new Coffee();
		Drink suger =new Suger(coffee); //装饰
		System.out.println(suger.info()+"-->"+suger.cost());
		Drink milk =new Milk(coffee);//装饰
		System.out.println(milk.info()+"-->"+milk.cost());		
		milk =new Milk(suger);//装饰
		System.out.println(milk.info()+"-->"+milk.cost());
	}
}
//抽象组件
interface Drink{
	double cost(); //费用
	String info(); //说明
}
//具体组件
class Coffee implements Drink{
	private String name ="原味咖啡";
	@Override
	public double cost() {
		return 10;
	}

	@Override
	public String info() {
		return name;
	}
	
}
//抽象装饰类
abstract class Decorate implements Drink{
	//对抽象组件的引用
	private Drink drink;
	public Decorate(Drink drink) {
		this.drink =drink;
	}
	@Override
	public double cost() {
		return this.drink.cost();
	}

	@Override
	public String info() {
		return this.drink.info();
	}	
}

//具体装饰类
class Milk extends Decorate{

	public Milk(Drink drink) {
		super(drink);
	}
	@Override
	public double cost() {
		return super.cost()*4;
	}

	@Override
	public String info() {
		return super.info()+"加入了牛奶";
	}	
}

class Suger extends Decorate{

	public Suger(Drink drink) {
		super(drink);
	}
	@Override
	public double cost() {
		return super.cost()*2;
	}

	@Override
	public String info() {
		return super.info()+"加入了蔗糖";
	}	
}

14.3 测试字节缓冲流 BufferedInputStream

	public static void main(String[] args) {
		File src = new File("abc.txt");
		//2、选择流
		InputStream  is =null;
		try {
			is =new BufferedInputStream(new FileInputStream(src));
			//3、操作 (分段读取)
			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);
			}		
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			//4、释放资源
			try {
				if(null!=is) {
					is.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}			
		}
	}
	public static void test1() {
		//1、创建源
		File src = new File("abc.txt");
		//2、选择流
		InputStream  is =null;
		BufferedInputStream bis =null;
		try {
			is =new FileInputStream(src);
			bis = new BufferedInputStream(is);
			//3、操作 (分段读取)
			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);
			}		
		
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			//4、释放资源
			try {
				if(null!=is) {
					is.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				if(null!=bis) {
					bis.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

14.4 测试字节缓冲流 BufferedOutputStream

		//1、创建源
		File dest = new File("dest.txt");
		//2、选择流
		OutputStream os =null;
		try {
			os =new BufferedOutputStream( new FileOutputStream(dest));
			//3、操作(写出)
			String msg ="IO is so easy\r\n";
			byte[] datas =msg.getBytes(); // 字符串-->字节数组(编码)
			os.write(datas,0,datas.length);
			os.flush();
		}catch(FileNotFoundException e) {		
			e.printStackTrace();
		}catch (IOException e) {
			e.printStackTrace();
		}finally{
			//4、释放资源
			try {
				if (null != os) {
					os.close();
				} 
			} catch (Exception e) {
			}
		}

14.5 测试字节缓冲流 BufferedWriter

		File src = new File("dest.txt");
		BufferedWriter writer = null;
		try {
			writer = new BufferedWriter(new FileWriter(src));
			writer.append("IO is so easy");
			writer.newLine();
			writer.append("将来的你一定会感谢今天努力的你");
			writer.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
	

14.6 测试字节缓冲流 BufferedReader

		File src = new File("abc.txt");
		BufferedReader rd = null;
		try {
			rd = new BufferedReader(new FileReader(src));
			String line = null;
			while ((line = rd.readLine()) != null) {
				System.out.println(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	

14.7 测试转换流 InputStreamReader OutputStreamWriter

		// 操作system.in 和system.out
		try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
				BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));) {
               // 循环获取键盘的输入(exit退出) 输出此内容
			String msg="";
			while(!msg.equals("exit")) {
				   msg=reader.readLine(); // 循环读取
				   writer.write(msg); // 循环写出
				   writer.newLine();
				   writer.flush(); // 强制刷新
				}
		} catch (Exception e) {
			System.out.println("操作异常");
		}

	

14.8 测试转换流 InputStreamReader OutputStreamWriter

public static void main(String[] args) {
		try(BufferedReader reader =new BufferedReader(new InputStreamReader(new URL("http://www.baidu.com").openStream(),"UTF-8"));
			BufferedWriter writer =new BufferedWriter(new OutputStreamWriter(new FileOutputStream("baidu.html"),"UTF-8"));){
			//3、操作 (读取)
			String msg ;
			while((msg=reader.readLine())!=null) {
				//System.out.println(msg);
				writer.write(msg); //字符集不统一不够出现乱码
				writer.newLine();
			}					
			writer.flush();
		}catch(IOException e) {
			System.out.println("操作异常");
		}
		
		
	}
	public static void test2() {
		//操作网络流  下载百度的源代码
		try(InputStreamReader is =new InputStreamReader(new URL("http://www.baidu.com").openStream(),"UTF-8");){
			//3、操作 (读取)
			int temp ;
			while((temp=is.read())!=-1) {
				System.out.print((char)temp);
			}		
			
		}catch(IOException e) {
			System.out.println("操作异常");
		}
	}
	public static void test1() {
		//操作网络流  下载百度的源代码
		try(InputStream is =new URL("http://www.baidu.com").openStream();){
			//3、操作 (读取)
			int temp ;
			while((temp=is.read())!=-1) {
				System.out.print((char)temp); //字节数不够出现乱码
			}		
			
		}catch(IOException e) {
			System.out.println("操作异常");
		}	
	}

14.9 测试数据流 DataOutputStream DataInputStream

		//写出
		ByteArrayOutputStream baos =new ByteArrayOutputStream();
		DataOutputStream dos =new DataOutputStream(new BufferedOutputStream(baos));
		//操作数据类型 +数据
		dos.writeUTF("编码辛酸泪");
		dos.writeInt(18);
		dos.writeBoolean(false);
		dos.writeChar('a');
		dos.flush();
		byte[] datas =baos.toByteArray();
		System.out.println(datas.length);
		//读取
		DataInputStream dis =new DataInputStream(new BufferedInputStream(new ByteArrayInputStream(datas)));
		//顺序与写出一致
		String msg = dis.readUTF(); 
		int age = dis.readInt();
		boolean flag = dis.readBoolean();
		char ch = dis.readChar();
		System.out.println(flag);
	

14.10测试对象流ObjectOutputStream ObjectInputStream

		//写出 -->序列化
		ByteArrayOutputStream baos =new ByteArrayOutputStream();
		ObjectOutputStream oos =new ObjectOutputStream(new BufferedOutputStream(baos));
		//操作数据类型 +数据
		oos.writeUTF("编码辛酸泪");
		oos.writeInt(18);
		oos.writeBoolean(false);
		oos.writeChar('a');
		//对象
		oos.writeObject("谁解其中味");
		oos.writeObject(new Date());
		Employee emp =new Employee("马云",400);
		oos.writeObject(emp);
		oos.flush();
		byte[] datas =baos.toByteArray();
		System.out.println(datas.length);
		//读取 -->反序列化
		ObjectInputStream ois =new ObjectInputStream(new BufferedInputStream(new ByteArrayInputStream(datas)));
		//顺序与写出一致
		String msg = ois.readUTF(); 
		int age = ois.readInt();
		boolean flag = ois.readBoolean();
		char ch = ois.readChar();
		System.out.println(flag);
		//对象的数据还原  
		Object str = ois.readObject();
		Object date = ois.readObject();
		Object employee = ois.readObject();
		
		if(str instanceof String) {
			String strObj = (String) str;
			System.out.println(strObj);
		}
		if(date instanceof Date) {
			Date dateObj = (Date) date;
			System.out.println(dateObj);
		}
		if(employee instanceof Employee) {
			Employee empObj = (Employee) employee;
			System.out.println(empObj.getName()+"-->"+empObj.getSalary());
		}
		// 写出 -->序列化
		ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("obj.ser")));
		// 操作数据类型 +数据
		oos.writeUTF("编码辛酸泪");
		oos.writeInt(18);
		oos.writeBoolean(false);
		oos.writeChar('a');
		// 对象
		oos.writeObject("谁解其中味");
		oos.writeObject(new Date());
		Employee emp = new Employee("马云", 400);
		oos.writeObject(emp);
		oos.flush();
		oos.close();
		// 读取 -->反序列化
		ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream("obj.ser")));
		// 顺序与写出一致
		String msg = ois.readUTF();
		int age = ois.readInt();
		boolean flag = ois.readBoolean();
		char ch = ois.readChar();
		System.out.println(flag);
		// 对象的数据还原
		Object str = ois.readObject();
		Object date = ois.readObject();
		Object employee = ois.readObject();

		if (str instanceof String) {
			String strObj = (String) str;
			System.out.println(strObj);
		}
		if (date instanceof Date) {
			Date dateObj = (Date) date;
			System.out.println(dateObj);
		}
		if (employee instanceof Employee) {
			Employee empObj = (Employee) employee;
			System.out.println(empObj.getName() + "-->" + empObj.getSalary());
		}
		ois.close();

14.11 测试随机读取写入流RandomAccessFile

public static void main(String[] args) throws IOException {
		 分多少块
		File src = new File("src/com/wshi/io/Copy.java");
		// 总长度
		long len = src.length();
		// 每块大小
		int blockSize = 1024;
		// 块数: 多少块
		int size = (int) Math.ceil(len * 1.0 / blockSize);
		System.out.println(size);

		// 起始位置和实际大小
		int beginPos = 0;
		int actualSize = (int) (blockSize > len ? len : blockSize);
		for (int i = 0; i < size; i++) {
			beginPos = i * blockSize;
			if (i == size - 1) { // 最后一块
				actualSize = (int) len;
			} else {
				actualSize = blockSize;
				len -= actualSize; // 剩余量
			}
			System.out.println(i + "-->" + beginPos + "-->" + actualSize);
			split(i, beginPos, actualSize);
		}

	}

	/**
	 * 指定第i块的起始位置 和实际长度
	 * 
	 * @param i
	 * @param beginPos
	 * @param actualSize
	 * @throws IOException
	 */
	public static void split(int i, int beginPos, int actualSize) throws IOException {
		RandomAccessFile raf = new RandomAccessFile(new File("src/com/sxt/io/Copy.java"), "r");
		// 随机读取
		raf.seek(beginPos);
		// 读取
		// 3、操作 (分段读取)
		byte[] flush = new byte[1024]; // 缓冲容器
		int len = -1; // 接收长度
		while ((len = raf.read(flush)) != -1) {
			if (actualSize > len) { // 获取本次读取的所有内容
				System.out.println(new String(flush, 0, len));
				actualSize -= len;
			} else {
				System.out.println(new String(flush, 0, actualSize));
				break;
			}
		}

		raf.close();
	}

	// 分开思想: 起始、实际大小
	public static void test2() throws IOException {
		RandomAccessFile raf = new RandomAccessFile(new File("src/com/sxt/io/Copy.java"), "r");
		// 起始位置
		int beginPos = 2 + 1026;
		// 实际大小
		int actualSize = 1026;
		// 随机读取
		raf.seek(beginPos);
		// 读取
		// 3、操作 (分段读取)
		byte[] flush = new byte[1024]; // 缓冲容器
		int len = -1; // 接收长度
		while ((len = raf.read(flush)) != -1) {
			if (actualSize > len) { // 获取本次读取的所有内容
				System.out.println(new String(flush, 0, len));
				actualSize -= len;
			} else {
				System.out.println(new String(flush, 0, actualSize));
				break;
			}
		}

		raf.close();
	}

	// 指定起始位置,读取剩余所有内容
	public static void test1() throws IOException {
		RandomAccessFile raf = new RandomAccessFile(new File("src/com/sxt/io/Copy.java"), "r");
		// 随机读取
		raf.seek(2);
		// 读取
		// 3、操作 (分段读取)
		byte[] flush = new byte[1024]; // 缓冲容器
		int len = -1; // 接收长度
		while ((len = raf.read(flush)) != -1) {
			System.out.println(new String(flush, 0, len));
		}

		raf.close();
	}
public static void main(String[] args) throws IOException {
		 分多少块
		File src = new File("src/com/wshi/io/Copy.java");
		// 总长度
		long len = src.length();
		// 每块大小
		int blockSize = 1024;
		// 块数: 多少块
		int size = (int) Math.ceil(len * 1.0 / blockSize);
		System.out.println(size);

		// 起始位置和实际大小
		int beginPos = 0;
		int actualSize = (int) (blockSize > len ? len : blockSize);
		for (int i = 0; i < size; i++) {
			beginPos = i * blockSize;
			if (i == size - 1) { // 最后一块
				actualSize = (int) len;
			} else {
				actualSize = blockSize;
				len -= actualSize; // 剩余量
			}
			System.out.println(i + "-->" + beginPos + "-->" + actualSize);
			split(i, beginPos, actualSize);
		}

	}

	/**
	 * 指定第i块的起始位置 和实际长度
	 * 
	 * @param i
	 * @param beginPos
	 * @param actualSize
	 * @throws IOException
	 */
	public static void split(int i, int beginPos, int actualSize) throws IOException {
		RandomAccessFile raf = new RandomAccessFile(new File("src/com/sxt/io/Copy.java"), "r");
		// 随机读取
		raf.seek(beginPos);
		// 读取
		// 3、操作 (分段读取)
		byte[] flush = new byte[1024]; // 缓冲容器
		int len = -1; // 接收长度
		while ((len = raf.read(flush)) != -1) {
			if (actualSize > len) { // 获取本次读取的所有内容
				System.out.println(new String(flush, 0, len));
				actualSize -= len;
			} else {
				System.out.println(new String(flush, 0, actualSize));
				break;
			}
		}

		raf.close();
	}

	// 分开思想: 起始、实际大小
	public static void test2() throws IOException {
		RandomAccessFile raf = new RandomAccessFile(new File("src/com/sxt/io/Copy.java"), "r");
		// 起始位置
		int beginPos = 2 + 1026;
		// 实际大小
		int actualSize = 1026;
		// 随机读取
		raf.seek(beginPos);
		// 读取
		// 3、操作 (分段读取)
		byte[] flush = new byte[1024]; // 缓冲容器
		int len = -1; // 接收长度
		while ((len = raf.read(flush)) != -1) {
			if (actualSize > len) { // 获取本次读取的所有内容
				System.out.println(new String(flush, 0, len));
				actualSize -= len;
			} else {
				System.out.println(new String(flush, 0, actualSize));
				break;
			}
		}

		raf.close();
	}

	// 指定起始位置,读取剩余所有内容
	public static void test1() throws IOException {
		RandomAccessFile raf = new RandomAccessFile(new File("src/com/sxt/io/Copy.java"), "r");
		// 随机读取
		raf.seek(2);
		// 读取
		// 3、操作 (分段读取)
		byte[] flush = new byte[1024]; // 缓冲容器
		int len = -1; // 接收长度
		while ((len = raf.read(flush)) != -1) {
			System.out.println(new String(flush, 0, len));
		}

		raf.close();
	}

14.2 面向对象思想:分割

// 源头
	private File src;
	// 目的地(文件夹)
	private String destDir;
	// 所有分割后的文件存储路径
	private List<String> destPaths;
	// 每块大小
	private int blockSize;
	// 块数: 多少块
	private int size;

	public SplitFile(String srcPath, String destDir) {
		this(srcPath, destDir, 1024);
	}

	public SplitFile(String srcPath, String destDir, int blockSize) {
		this.src = new File(srcPath);
		this.destDir = destDir;
		this.blockSize = blockSize;
		this.destPaths = new ArrayList<String>();

		// 初始化
		init();
	}

	// 初始化
	private void init() {
		// 总长度
		long len = this.src.length();
		// 块数: 多少块
		this.size = (int) Math.ceil(len * 1.0 / blockSize);
		// 路径
		for (int i = 0; i < size; i++) {
			this.destPaths.add(this.destDir + "/" + i + "-" + this.src.getName());
		}
	}

	/**
	 * 分割 1、计算每一块的起始位置及大小 2、分割
	 * 
	 * @throws IOException
	 */
	public void split() throws IOException {
		// 总长度
		long len = src.length();
		// 起始位置和实际大小
		int beginPos = 0;
		int actualSize = (int) (blockSize > len ? len : blockSize);
		for (int i = 0; i < size; i++) {
			beginPos = i * blockSize;
			if (i == size - 1) { // 最后一块
				actualSize = (int) len;
			} else {
				actualSize = blockSize;
				len -= actualSize; // 剩余量
			}
			splitDetail(i, beginPos, actualSize);
		}
	}

	/**
	 * 指定第i块的起始位置 和实际长度
	 * 
	 * @param i
	 * @param beginPos
	 * @param actualSize
	 * @throws IOException
	 */
	private void splitDetail(int i, int beginPos, int actualSize) throws IOException {
		RandomAccessFile raf = new RandomAccessFile(this.src, "r");
		RandomAccessFile raf2 = new RandomAccessFile(this.destPaths.get(i), "rw");
		// 随机读取
		raf.seek(beginPos);
		// 读取
		// 3、操作 (分段读取)
		byte[] flush = new byte[1024]; // 缓冲容器
		int len = -1; // 接收长度
		while ((len = raf.read(flush)) != -1) {
			if (actualSize > len) { // 获取本次读取的所有内容
				raf2.write(flush, 0, len);
				actualSize -= len;
			} else {
				raf2.write(flush, 0, actualSize);
				break;
			}
		}
		raf2.close();
		raf.close();
	}

	/**
	 * 文件的合并
	 * 
	 * @throws IOException
	 */
	public void merge(String destPath) throws IOException {
		// 输出流
		OutputStream os = new BufferedOutputStream(new FileOutputStream(destPath, true));
		Vector<InputStream> vi = new Vector<InputStream>();
		SequenceInputStream sis = null;
		// 输入流
		for (int i = 0; i < destPaths.size(); i++) {
			vi.add(new BufferedInputStream(new FileInputStream(destPaths.get(i))));
		}
		sis = new SequenceInputStream(vi.elements());
		// 拷贝
		// 3、操作 (分段读取)
		byte[] flush = new byte[1024]; // 缓冲容器
		int len = -1; // 接收长度
		while ((len = sis.read(flush)) != -1) {
			os.write(flush, 0, len); // 分段写出
		}
		os.flush();
		sis.close();
		os.close();
	}

	public static void main(String[] args) throws IOException {
		SplitFile sf = new SplitFile("src/com/sxt/io/SplitFile.java", "dest");
		sf.split();
		sf.merge("aaa.java");
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值