学习Java_IO_File看这篇就够了(2万多字的教程)

好文推荐:排序、查找算法齐全(程序员必会 好文 值得收藏!)

  • 想必阅读这篇文章的都应该学过java或者正在学习的路上,java中的IO可是非常重要的知识点,以后的工作都需用到它。话不多说,简单的来说:上传和下载就是IO(其中I代表Input、O代表output)。
  • IO操作的8大类: 文件类(File)、字节输入流(InputStream)、字节输出流(OutputStream)、字符输入流(Reader)、字符输出流(Writer)、关闭流接口(Closeable)、刷新流接口(Flushable)、序列化接口(Serializable)。

1、IO_File入门

1)知识点:文件路径的操作方式

		String path1;
		String path2;
		System.out.println(File.separator);  //测试分隔符

个人建议:写路径时使用分隔符!

说明:此次分享,含有代码但没运行结果!想要的话,自己动手打开电脑中的eclipse,运行即可。强调一点:实践才能出真知!

  • 方式一
		path1="D:\\MyPicture\\logo.png";
		System.out.println(path1);  //结果自己运行
  • 方式二:常量拼接(强烈推荐)
        path2="D:"+File.separator+"MyPicture"+File.separator+"logo.png";
		System.out.println(path2);  

2)知识点:构建File对象方式

String path="D:\\MyPicture\\logo.png";
  • 方式一
		File file=new File(path);
		System.out.println(file.length());
  • 方式二
		file=new File("D:\\MyPicture\\logo.png");
		System.out.println(file.length());
  • 方式三
		file=new File(new File("D:\\MyPicture"),"logo.png");
		System.out.println(file.length());

3)知识点:相对路径和绝对路径

String path3="D:\\MyPicture\\logo.png";
  • 绝对路径
		File src=new File(path3);
		System.out.println(src.getAbsolutePath());
  • 相对路径
		System.out.println(System.getProperty("user.dir"));
		src=new File("logo.png");
		System.out.println(src.getAbsolutePath());

2、IO_File常见操作

1)知识点:常用方法

		File file2=new File("D://图片//test.png");
		System.out.println("名称:"+file2.getName());
		System.out.println("路径:"+file2.getPath());
		System.out.println("绝对路径:"+file2.getAbsolutePath());
		System.out.println("父路径:"+file2.getParent());
		System.out.println("父对象:"+file2.getParentFile().getName());

2)知识点:文件状态

		System.out.println("是否存在:"+file2.exists());
		System.out.println("是否文件:"+file2.isFile());
		System.out.println("是否文件夹:"+file2.isDirectory());

3)知识点:其他操作

		boolean flag;
		try {
			flag = file2.createNewFile();
			System.out.println(flag);  
			flag=file2.delete();
			System.out.println(flag);
		} catch (IOException e) {
			e.printStackTrace();
		}

温馨提示:createFile():不存在创建,存在创建成功,不是文件夹!delete():删除已经存在的文件!

3、IO_File_文件夹创建_遍历

1)知识点:mkdir和mkdirs的区别

File dir=new File("C:\\Users\\Tjink\\eclipse-workspace\\StudyJDBC\\src\\test1");
  • mkdir创建目录
		boolean flag2=dir.mkdir();
		System.out.println(flag2);  
  • mkdirs创建目录
		dir=new File("C:\\Users\\Tjink\\eclipse-workspace\\StudyJDBC\\src\\test2");
		flag=dir.mkdirs();
		System.out.println(flag);

结论:你运行之后,推导出来了吗?
mkdir():确保上级目录存在,不存在创建失败。 mkdirs():上级目录可以不存在,不存在就创建。

2)知识点:列出下级

File dir2=new File("C:\\Users\\Tjink\\eclipse-workspace\\StudyJDBC");
  • 下级名称 list
		String[] subNames=dir2.list();
		for(String s:subNames) {
			System.out.println(s);
		}
  • 下级对象 listFiles()
		File[] subFiles=dir2.listFiles();
		for(File s:subFiles) {
			System.out.println(s);
		}
  • 所有盘符
		File[] roots=dir2.listRoots();
		for(File r:roots) {
			System.out.println(r);
		}

结论:list():列出下级名称。listFiles():列出下级对象。

4、IO_File_字符集_乱码

我们都应该知道,从字符串到字节称之为“编码”,反之,称之为“解码”。

1)知识点:测试

		String msg="努力加油学习y";
		byte[] datas=msg.getBytes();  //默认使用工程的字符集
		System.out.println(datas.length);  

2)知识点:编码:其他字符集

	try {
			datas=msg.getBytes("UTF-16LE");  
			System.out.println(datas.length);
			datas=msg.getBytes("GBK");
			System.out.println(datas.length);  
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

3)知识点:解码

	try {
			msg=new String(datas,0,datas.length,"GBK");
			System.out.println(msg);  
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

4)补充!非常重要 乱码问题分析解决方案

  • ①原因one:字节数不够!
	try {
			msg=new String(datas,0,datas.length-2,"GBK");
			System.out.println(msg);  
			msg=new String(datas,0,datas.length-1,"GBK");
			System.out.println(msg);  
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
  • ②原因two:字符集不统一!
	try {
			msg=new String(datas,0,datas.length,"utf8");
			System.out.println(msg);  
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

说明:此次java运行环境为eclipse,默认编码集为GBK。

5、IO_四大抽象类

在这里插入图片描述

6、IO_标准步骤

简单的说,4个步骤:创建源、选择流、操作、释放。

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

7、IO_文件字节流

1)知识点:文件字节输入流

		//1、创建源
		File src2=new File("gg.txt");
		//2、选择流
		InputStream is2=null;
		try {
			is2=new FileInputStream(src2);
			//3、操作(分段读取)
			byte[] flush=new byte[1024];  //缓冲容器
			int len=-1;  //接收长度
			while((len=is2.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 {
			try {
				if(null!=is2) {
					is2.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

2)知识点:文件字节输出流

		//1、创建源
		File dest=new File("dest.txt");
		//2、选择流
		OutputStream os=null;
		try {
			os= new FileOutputStream(dest); //可以追加,后面加true追加,
			//3、操作(写出)
			String msg="IO is so easy";
			byte[] datas=msg.getBytes(); //字符串-->字节(编码)
			os.write(datas,0,datas.length);
			os.flush();
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}catch (IOException e) {
			e.printStackTrace();
		}finally {
			if(null!=os) {
				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

8、IO_文件拷贝

这里提供文件拷贝的方法!

	public static void copy(String path,String destPath) {
		//1、创建源
		File src=new File(path);  //源头
		File dest=new File(destPath);  //目的地
		//2、选择流
		InputStream is=null;
		OutputStream os=null;
		try {
			is=new FileInputStream(src);
			os=new FileOutputStream(dest);
			//3、操作(分段读取)
			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 {
			if(null!=os) {
				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(null!=is) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}	
	}

9、IO_文件流

1)知识点:文件字符输入流

		//1、创建源
		File src3=new File("gg.txt");
		//2、选择流
		Reader reader=null;
		try {
			reader=new FileReader(src3);
			//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 (FileNotFoundException e) {
			e.printStackTrace();
		}catch (IOException e) {
			e.printStackTrace();
		}finally {
			if(null!=reader) {
				try {
					reader.close();
				} catch (IOException e) {

					e.printStackTrace();
				}
			}
		}

2)知识点:文件字符输出流

方法操作同文件字节输出流类似,读者可以尝试着自己写下!

		//1、创建源
		File dest2=new File("dest.txt");
		//2、选择流
		Writer writer=null;
		try {
			writer=new FileWriter(dest2);
			//3、操作(写出)
			//写法一
//					String msg="IO is so easy!\n";
//					char[] datas=msg.toCharArray();  //字符串--字符数组
//					writer.write(datas,0,datas.length);
			//写法二
//					String msg="IO is so easy!hahahh";
//					writer.write(msg);
//					writer.write("add"); //写多次
			//写法三
			writer.append("IO is so easy").append("加油啊");
			writer.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if(writer!=null) {
				try {
					writer.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}	

10、字节数组流

1)知识点:字节输入流

		//1、创建源:字节数组
		byte[] src4="talk is cheap show me the code".getBytes();
		//2、选择流
		InputStream is3=null;
		is3=new ByteArrayInputStream(src4);
		//3、操作(分段读取)
		byte[] flush=new byte[50];  //缓冲容器
		int len =-1;
		try {
			while((len=is3.read(flush))!=-1) {
				String str=new String(flush,0,len);
				System.out.println(str);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				if(null!=is3) {
					is.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

2)知识点:字节输出流

		//1、创建源
		byte[] dest3=null;
		//2、选择流(新增方法)
		ByteArrayOutputStream baos=null;
		try {
			baos=new ByteArrayOutputStream();
			//3、操作(写出)
			String msg="show me the code";
			byte[] datas=msg.getBytes();  //字符串-->字节数组(编码)
			baos.write(datas,0,datas.length);
			baos.flush();
			//获取数据
			dest3=baos.toByteArray();
			System.out.println(dest3.length+"-->"+new String(dest3,0,baos.size()));
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			//4、释放资源
			if(null!=baos) {
				try {
					baos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

11、IO_综合_对接流

	/*
	 * 1、图片读取到字节数组中
	 * 1)图片到程序 FileInputStream
	 * 2)程序到字节数组 ByteArrayOutputStream
	 */
	public static byte[] fileToByteArray(String filePath) {
		//1、创建源与目的地
		File src=new File(filePath);
		byte[] dest=null;
		//2、选择流
		InputStream is=null;
		ByteArrayOutputStream baos=null;
		try {
			is=new FileInputStream(src);
			baos=new ByteArrayOutputStream();
			//3、操作(分段读取)
			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 (FileNotFoundException e) {
			e.printStackTrace();
		}catch (IOException e) {
			e.printStackTrace();
		}finally {
			if(null!=baos) {
				try {
					baos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(null!=is) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
		
	}
	public static void byteArrayToFile(byte[] src,String filePath) {
		/*
		 * 2、字节数组写出到图片
		 * 1)字节数组道程序 ByteArrayInputStream
		 * 2)程序到文件 FileOutputStream
		 */
		//1、创建源
		File dest=new File(filePath);
		//2、选择流
		InputStream is=null;
		OutputStream os=null;
		try {
			is=new ByteArrayInputStream(src);
			os=new FileOutputStream(dest);
			//3、操作(分段读取)
			byte[] flush=new byte[5];
			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、释放资源
			if(null!=os) {
				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(null!=is) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		/*
		 * ceshi
		 */
		byte[] datas=fileToByteArray("dest.txt");
		System.out.println(datas.length);  //-->19
		byteArrayToFile(datas,"p-byte");	

12、IO_原理解析_装饰器设计模式

  • 案例1
public class Test01 {
	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());
	}
	public int getVoice() {
		return voice;
	}
	public void setVoice(int voice) {
		this.voice=voice;
	}
}
class Amplifier implements Say{
	private Person p;
	Amplifier(Person p){
		this.p=p;
	}
	public void Say() {
		System.out.println("人的声音为:"+p.getVoice()*100);
		System.out.println("噪音。。。。");
	}
}
  • 案例2:模拟咖啡
    1)抽象组件:需要装饰的抽象对象(接口或抽象父类)
    2)具体组件:需要装饰的对象
    3)抽象装饰类:包含了对抽象组件的引用以及装饰着共有的方法
    4)具体装饰类:被装饰的对象
public class Test02 {
	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()+"加入了红糖";
	}
}

13、IO_字节缓冲流

加入缓冲流:性能提升、处理时间缩短。
四个步骤:分段读取 文件字节输入流 加入缓冲流。

  • 1、创建源
  • 2、选择流
  • 3、操作
  • 4、释放资源
public class BUfferedTest03 {
	public static void main(String[] args) {
		//1、创建源
		File src=new File("dest.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、释放资源
			if(null!=is) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(null!=bis) {
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
	}
}

14、IO_字符缓冲流

public class Test5 {
	public static void main(String[] args) {
		//1、创建源
		File src=new File("dest.txt");
		//2、选择流
		BufferedReader reader=null;
		try {
			reader=new BufferedReader(new FileReader(src));
			//3、操作 逐行读取
			String line=null;
			while((line=reader.readLine())!=null) {
				System.out.println(line);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}catch (IOException e) {
			e.printStackTrace();
		}finally {
			if(null!=reader) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

15、IO_转换流_字符集

转换流:InputStreamReader OutputStreamWriter

  • 1、以字符流的形式操作字节流(纯文本的)
  • 2、指定字符集
public class Test06 {
	public static void main(String[] args) {
		BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(System.out));
		//循环获取键盘的输入(exit退出)。输出此内容
		String msg="";
		while(!msg.equals("exit")) {
			try {
				msg=reader.readLine(); //循环读取
				writer.write(msg);  //循环写出
				writer.newLine();
				writer.flush();  //强制刷新
			} catch (IOException e) {
				e.printStackTrace();
			}  
		}
	}
}
public class Test7 {
	public static void main(String[] args) {
		//操作网络流
		try {
			BufferedReader reader=new BufferedReader(new InputStreamReader(new URL("http://wwww.baidu.com").openStream(),"UTF-8"));
			//3、操作(读取)
			String msg;
			while((msg=reader.readLine())!=null) {
				System.out.println(msg);
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
}

16、IO_数据流

数据流:

  • 1、写出后读取
  • 2、读取的顺序与写出保持一致
  • DataOutputStream
  • DataInputStream
public class Test1 {
	public static void main(String[] args) throws IOException {
		//写出
		ByteArrayOutputStream baos=new ByteArrayOutputStream();
//		DataOutputStream dos=new DataOutputStream(baos);
		DataOutputStream dos=new DataOutputStream(new BufferedOutputStream(baos));
		//操作数据类型+数据
		try {
			dos.writeUTF("编码好有趣");
			dos.writeInt(18);
			dos.writeBoolean(false);
			dos.writeChar('a');
			dos.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
		byte[] datas=baos.toByteArray();
		System.out.println(datas.length);  //-->24
		//读取
//		DataInputStream dis=new DataInputStream(new ByteArrayInputStream(datas));
		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);  //-->false
	}
}

17、IO_对象流

对象流

  • 1、写出后读取
  • 2、读取的顺序与写出保持一致
  • 3、不是所有的对象都可以序列化Serializable
  • ObjectOutputStream
  • ObjectInputStream
    说明:代码有些问题,没得到正确的输出。输出时有异常!!!如果哪位大佬知道哪里出错,帮帮忙,留言评论吧。
public class Test2 {
	public static void main(String[] args) throws ClassNotFoundException, Exception {
		try {
			//写出
			ByteArrayOutputStream baos=new ByteArrayOutputStream();
			ObjectOutputStream dos=new ObjectOutputStream(new BufferedOutputStream(baos));
			//操作数据类型+数据
			dos.writeUTF("编码好有趣");
			dos.writeInt(18);
			dos.writeBoolean(false);
			dos.writeChar('a');
			//对象
			dos.writeObject("码农级别");
			dos.writeObject(new Date());
			Employee emp=new Employee("码云",40000);
			dos.writeObject(emp);
			dos.flush();
			byte[] datas=baos.toByteArray();
			System.out.println(datas.length);  //-->177
			//读取
			ObjectInputStream dis=new ObjectInputStream(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);  //-->false
			Object str=dis.readObject();
			Object date=dis.readObject();
			Object employee=dis.readObject();
			
			if(str instanceof String) {
				String strObj=(String)str;
				System.out.println(strObj);
			}
			if(date instanceof Date) {
				Date dateObj=(Date)str;
				System.out.println(dateObj);
			}
			if(employee instanceof Employee) {
				Employee empObj=(Employee)str;
				System.out.println(empObj.getName()+"-->"+empObj.getSalary());
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
}
//javabean封装数据
class Employee implements java.io.Serializable{
	private String name;
	private double salary;
	public Employee() {
		
	}
	public Employee(String name, double salary) {
		super();
		this.name = name;
		this.salary = salary;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public double getSalary() {
		return salary;
	}
	public void setSalary(double salary) {
		this.salary = salary;
	}
	
}

18、IO_打印流

1)打印流 PrintStream

public class Test3 {
	public static void main(String[] args) {
		//打印流System.out
		PrintStream ps=System.out;  //默认输出到控制台
		ps.println("打印流");
		ps.println(true);
		try {
			ps=new PrintStream(new BufferedOutputStream(new FileOutputStream("dest2.txt")),true);
			ps.print("打印流");
			ps.println(true);
			ps.close();
//			ps.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		//重定向输出端
		System.setOut(ps);
		System.out.println("change");
		//重定向回控制台
		System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream(FileDescriptor.out)),true));
		System.out.println("I am backing");
	}
}

2)打印流 PrintWriter

public class Test4 {
	public static void main(String[] args) {
		try {
			PrintWriter pw=new PrintWriter(new BufferedOutputStream(new FileOutputStream("dest2.txt")),true);
			pw.println("打印流");
			pw.println(true);
			pw.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}
	
}

19、IO_文件分割_面向过程核心板

1)随机读取和写入流 RandomAccessFile

public class Test5 {
	public static void main(String[] args) {
		try {
			RandomAccessFile raf=new RandomAccessFile("src/com/TestIo/Test.java","r");
			//起始位置
			int beginPos=2;
			//实际大小
			int actualSize=1026;
			//随机读取
			raf.seek(beginPos);
//			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));
				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();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
}

public class Test6 {
	public static void main(String[] args) {
		//分多少块
		File src=new File("src/com/TestIo/Test.java");
		//总长度
		long len=src.length();
		//每块大小
		int blockSize=300;
		//多少块
		int size=(int)Math.ceil(len*1.0/blockSize);
		System.out.println(size);  //-->2
		
		//起始位置和实际大小
		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);
		}
	}
}

20、IO_CommonsIO_环境搭建

  • 官网:apache.org 下载对应的jar

  • 官网链接

  • 进阶:jar—>组件—>框架*
    下载教程:

  • 第一步:进入官网
    在这里插入图片描述

  • 第二步,找到Commons,点击进入
    在这里插入图片描述

  • 第三步,点击IO
    在这里插入图片描述

  • 第四步,下载最新版
    在这里插入图片描述
    在这里插入图片描述

21、IO_CommonsIO_核心操作

/*
 * 大小
 */
public class Test {
	public static void main(String[] args) {
		//文件大小
		long len=FileUtils.sizeOf(new File("src\\com\\StudyCommons\\Test.java"));
		System.out.println(len);
		//目录大小
		len=FileUtils.sizeOf(new File("C:\\Users\\Tjink\\eclipse-workspace\\IO_Study"));
		System.out.println(len);
	}
}

/*
 * 列出子孙级
 */
public class Test{
	public static void main(String[] args) {
		Collection<File> files=FileUtils.listFiles(new File("C:\\Users\\Tjink\\eclipse-workspace\\IO_Study"),EmptyFileFilter.NOT_EMPTY,null);
		for(File file:files) {
			System.out.println(file.getAbsolutePath());
		}
	}
}

22、IO_CommonsIO_拷贝核心操作

/*
 * 拷贝
 */
public class Test{
	public static void main(String[] args) {
		try {
			//复制文件
			FileUtils.copyFile(new File("src/com/StudyCommons/1.jpeg"),new File("p-copy.jpeg"));
			//复制文件到目录
			FileUtils.copyFileToDirectory(new File("src/com/StudyCommons/1.jpeg"),new File("lib"));
			//复制目录到目录
			FileUtils.copyDirectoryToDirectory(new File("lib"),new File("lib2"));
			//复制目录
			FileUtils.copyDirectory(new File("lib"),new File("lib2"));
			//拷贝URL内容
			String url="https://wwww.baidu.com";
			FileUtils.copyURLToFile(new URL(url),new File("marver.txt"));
			//输出字符串URL
			String datas=IOUtils.toString(new URL("http://www.baidu.com"),"UTF-8");
			System.out.println(datas);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
}
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值