day17 异常、File类、io流

在学习io流之前,先了解异常类和File类

一.异常类

    1.先通过以下例子了解异常: 

                有一个班长骑车出去旅行
   1)在骑行的过程中,前方的山路坍塌了,导致它不能骑行了------>不可抗力的因素
   2)在骑行的过程中,发现轮胎没气了,也会出现问题----------->骑行志强应该检查的问题
   3)山路两边是石子,中间是平坦的大道,但是班长就喜欢在边上骑行,导致轮胎没气;------>no zuo no die
 
  
    出现第一种情况:严重问题,不处理---->开发中:内存溢出! 开发团队,集体研究这个问题!(假设加载大量图片的时              候:ImageLoader)


    大的方向:Throwable
    两个具体的子类:
    Error  Exception
  
         第二种情况和第三种情况都属于异常的范畴:


    Exception的分类:异常类
    子类:
         1)编译时期异常:只要不是RuntimeException中的异常都属于编译时期异常:比如:IOException(IO流中                              的),ParseException(解析异常)
       出现的原因:要么语法有问题,要么使用的是Sun公司提供的一些类的中的方法,(这个方法本身调用的时候就会异            常存在),调用者必须处理,不处理不行,需要编译通过
     2)运行时期异常:RuntimeException
       可能由于我们代码的逻辑不够严谨导致的问题举例,NullPointerException:空指针异常!
        需要个对象进行非空判断,来防止该问题的出现!

  
 2.如何处理异常?
   分为两种方式:
   1)标准格式:try...catch...finally:捕获异常!
   2)throws 抛出异常
  
  首先:方式1:处理异常:
   try...catch...finally
   变形格式:
   try...catch
   try...catch...catch
   try...finally...(多线程的时候:Lock锁)
  经常使用的格式:
  try{
   //可能有很多行代码---->一旦有出现问题了
  }catch(异常类名 变量名){
   输出语句处理
  }


例子:

public class ExceptionDemo2 {
	
	public static void main(String[] args) {
		//定义两个变量
		
		int a = 10 ;
		int b = 0 ;
		
		
		int[] arr = {1,2,3} ;
		//输出
		
			try {
				//try中:是可能会出现问题的代码
				System.out.println(a/b);
				//针对问题给出具体的异常类:
			} catch (Exception e) {
//				e.printStackTrace();
				System.out.println("除数不能为0");
			}
		
		System.out.println("over");
	}
}

3.如果有多个异常存在,如何处理呢?
  
   1)方式1:
   针对多个异常分别的try...catch :在实际开发中,这种做法比较麻烦
   2)方式2:
  
   try{
   可能会出现问题的多个语句
   }catch(异常类名1 变量名){
   输出语句处理
   }catch(异常类名2 变量名){
   输出语句处理
   }
 例子:

public class ExceptionDemo3 {
	
	public static void main(String[] args) {
		
//		method1();
		
//		method2();
		
		method3() ;
	/*	
	 * 
	 * 针对多个异常进行处理,第一个异常如果是大异常,那么后面可以不用再给了!
	 * 将大异常放在小异常的后面;
	 * 
		int a = 10 ;
		int b = 0 ;
		int[] arr = {1,2,3} ;
		
		try{
			//可能出现问题的代码
			System.out.println(arr[3]);
			System.out.println(a/b);
		}catch(Exception e){
			System.out.println("可能会出现问题");
		}catch(ArrayIndexOutOfBoundsException e){
			System.out.println("您访问了数组中不存在的索引");
		}catch(ArithmeticException e){
			System.out.println("除数不能玩为0");
		}
		
		System.out.println("over");*/
		
	}
	
	
	private static void method3() {

		int a = 10 ;
		int b = 0 ;
		int[] arr = {1,2,3} ;
		
		try{
			//可能出现问题的代码
			System.out.println(arr[3]);
			System.out.println(a/b);
		}catch(ArrayIndexOutOfBoundsException e){
			System.out.println("您访问了数组中不存在的索引");
		}catch(ArithmeticException e){
			System.out.println("除数不能玩为0");
		}catch(Exception e){
			System.out.println("程序可能出现问题了");
		}
		
		System.out.println("over");
	}


	//多个异常一块进行处理,只要try语句中的代码和catch语句中的代码所描述的异常类的信息一致,那么直接走catch里面的代码,try...catch语句结束
	private static void method2() {
		//定义变量以及数组
		int a = 10 ;
		int b = 0 ;
		int[] arr = {1,2,3} ;
		
		try{
			//可能出现问题的代码
			System.out.println(arr[3]);
			System.out.println(a/b);
		}catch(ArithmeticException e){
			System.out.println("除数不能为0");
		}catch(ArrayIndexOutOfBoundsException e){
			System.out.println("您访问了数组中不存在的索引");
		}
		
		System.out.println("over");
	}
	
	//针对多个异常分别的进行try...catch
	private static void method1() {
		//定义一个变量
		int a = 10 ;
		int b = 0 ;
		
		//第一个异常
		try {
			System.out.println(a/b);
		} catch (ArithmeticException e) {
			//输出语句处理
			System.out.println("除数不能为0");
		}
		
		//定义一个数组
		int[] arr = {1,2,3} ;
		try{
			System.out.println(arr[3]);
		}catch(ArrayIndexOutOfBoundsException e){
			System.out.println("您访问了数组中不存在的索引");
		}
		
		System.out.println("over");
	}
}
4针对多个异常进行处理,Jdk7以后又一种新的处理方式:
  try{
  //可能会出现问题的代码
  //....
  //...
  }catch(异常类名1 | 异常类名2 ....变量名){
  处理异常...
  }
  这个格式的注意事项:
  1)针对多个异常类名之间是一种平级关系
  2)这种格式在实际开发中,虽然有多个异常,但是针对具体的异常给出具体的处理!    例子:
public class ExceptionDemo4 {
	
	public static void main(String[] args) {
		
		//定义变量及数组
		int a = 10 ; 
		int b = 0 ;
		int[] arr = {1,2,3} ;
		
		try{
			System.out.println(a/b);
			System.out.println(arr[3]);
		}catch(ArithmeticException | ArrayIndexOutOfBoundsException  e){
//			System.out.println("程序出问题了...");
			e.printStackTrace() ;
		}
		
		System.out.println("over");
		
	}
}

5.如何处理编译时期异常和运行时期异常

      编译时期:Java程序必须给予处理,否则编译不通过(必须显示处理)

      运行时期异常:可以处理,也可以像编译时期一样进行显示处理!

      

       例子:

public class ExceptionDemo {
	
	public static void main(String[] args) {
		
		
		int a = 10 ;
		int b = 0 ;
		if(b!=0){
			System.out.println(a/b);
		}
		
		
		System.out.println("今天天气很好");
		
	
			method() ;
		
		
		
		System.out.println("但是不应该又雾霾...");
	}
	
	
	
	
	//调用Parse这个方法,本身就会抛出一个异常!
	//注意:告诉调用者,注意了,我有问题;在main()中也必须处理
	private static void method()  {
		
		//String日期"文本"格式---->Date格式:解析
		String s = "2018-6-25" ;
		//创建SimpleDataFormat对象
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd") ;
		//调用parse()方法
			Date d;
			try {
				d = sdf.parse(s);
				System.out.println("d:"+d); 
			} catch (ParseException e) {
//				e.printStackTrace();//异常中的方法
				System.out.println("解析出问题了...");
			}
			
	}
}

6.try里面的代码一旦出问题了,那么Jvm java虚拟机就会针对这个问题抛出一个异常,然后和Catch里面的所描述异常进行是否匹配,如果一致就会产生一个异常对象,然后去处理这个异常对象,就会调用异常中的一些方法
 
  try{
   可能有问题的代码
  }catch(异常类名 变量名){
   ...
  }
  
  常用的方法:
   public String getMessage()
   消息字符串
   public String toString()
   描述字符串:
   1)当前类的全路径名称(指的是当前异常类名所在的包的全路径名称)
   2)": "(冒号和一个空格)
  
   public void printStackTrace():
   该方法是里面包含了消息字符串以及当前出现错误的异常的时候所描述哪个包下以及代码中                                         具体的错误出现第几行
   返回值是void,也就直接在控制台输出

      例子:

public class ExceptionDemo2 {
	public static void main(String[] args) {
		
		//解析日期的文本格式
		String str = "2014-5-20" ;
		//创建SimpleDataFormat对象
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd") ;
		
		try {
			Date date = sdf.parse(str) ;//这里面的代码一旦有问题,Jvm就会抛出一个异常,和Catch里面进行匹配,如果一致
			//就会产生一个异常对象
			System.out.println(date);
		} catch (ParseException e) {//ParseException e = new ParseException() ;
//			e.printStackTrace();
			//getMessage():消息字符串
//			System.out.println(e.getMessage()) ;
			//Unparseable date: "2014-5-20"
			
//			System.out.println(e.toString());
			
			e.printStackTrace();//相当于给出了一个页面
		}
		System.out.println("over");
	}
}

7.异常处理第二种方式:
   throws:抛出异常
  
   在方法声明上抛出异常,由于,编译时期异常,调用者必须要处理
  
  实际开发中,尽量的不要在main()方法抛出异常,在子方法中可以抛出异常。
  
  面试题:(1000%问到)
   throws和throw的区别?
  
   throws:抛出
后面跟的异常类名,可以跟多个异常类名,中间用逗号隔开
   throws在方法声明上抛出,表示异常的一种可能性
   由调用者去处理
   throws表示抛出异常的一宗可能性
   throw:抛出
   后面跟的异常对象(匿名对象),只能跟具体的一个异常对象
   throw在方法中的语句中抛出,表示异常的绝对性
   有方法中某些语句处理
  
  在实际开发中:
   throws要比throw用的比较多,而try...catch...又比throws用的比较多!


例子:

public class ExceptionDemo3 {
	
	public static void main(String[] args) throws ParseException,ArithmeticException{
		
		//告诉调用者,抛出异常了,所以这里必须处理
		method();
		
		try {
			method2();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//throw
	private static void method2() throws Exception {
		int a = 10 ;
		int b = 0 ;
		if(b==0){
			System.out.println(a/b);
			throw new ArithmeticException() ;//跟的异常对象
		}else{
			System.out.println("不会出现问题");
		}
	}

	private static void method() throws ParseException {
		String str = "2017-11-19" ;
		
		//创建SimpleDataFormat对象
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd") ;
		
		//解析
		Date d = sdf.parse(str) ;
		
		System.out.println(d);
	}
}


8.经常会看到这种格式:
   捕获异常的标准格式: try...catch...finally
  用法:
   finally经常用在数据库中或者IO流中,用来释放资源的
   finally中的代码一定会执行.
  
   finally中的不执行只有一种情况:就是Jvm退出了---------->System.exit(0) ;
  
   面试题:
   final,finalize,和finally的区别?
   区别:
   final:表示最终的,终态的意思
   可以修饰类:类不能继承
   可以修饰成员方法:成员方法被重写
   可以修饰成员变量:此变量是一个常量 :自定义常量:  public static final int ORANGLE = 100 ;
   finalize:它表示通过gc垃圾回收器回收不用的对象或者是变量,System.gc():实质,调用的是重写了                    Object类中的finalize()方法,表示回收没有跟多引用对象或者变量等等...
    finally:不能单独使用,和try...catch...finally中一块使用,(异常,IO,数据库中中使用的),是用来释放资源
   finally中的代码一定会执行,并且除非Java虚拟机Jvm退出了,才不会执行!


9.面试题:
  如果catch里面有return语句,那么finally中的代码还会执行吗?
   如果可以,是在return前执行还是return后执行?
   会执行;并且在return 前执行!

例子:

public class FinallyDemo2 {
	


	public static void main(String[] args) {
		System.out.println(getInt());
	}

	
	//方法
	private static int getInt() {
		int a = 10 ;
		try{
			System.out.println(a/0);
			a = 20 ;
		}catch(ArithmeticException e){
			a = 30 ;
			return a ;
			/**
			 * 代码走到这里,return a,return 30 ,在这里形成了一个方法返回路径
			 * 但是,finally中代码只有在Jvm退出了,才不会执行,所以a = 40 ;
			 * 但是,由于之前已经返回路径,代码就要执行到return 前;
			 */
		}finally{
			a = 40 ;
			
		}
		return a;
		
	}
}

10.自定义异常类

   实际开发中不可能一直使用已经提供了的异常类,有时候需要自己定义一个异常类?
   如何自定义一个异常类?
   自定义一个类,继承自Exception或者继承自RuntimeException
   例子:

public class MyException extends Exception {
	
	public MyException(){
		
	}
	
	public MyException(String message){
		super(message) ;
	}
	
}

public class StudentDemo {
	
	public static void main(String[] args) {
		
		//创建键盘录入对象
		Scanner sc = new Scanner(System.in) ;
		
		System.out.println("请您输入一个分数:");
		int score = sc.nextInt() ;
		
		//创建Teacher对象
		Teacher t = new Teacher() ;
		try {
			t.check(score) ;
		} catch (MyException e) {
			e.printStackTrace();
		}
	}
	
}

public class Teacher {
	
	public void check(int score) throws MyException{
		//针对分数进行判断
		if(score>100 || score<0){
			throw new MyException("分数应该在0和100之间") ;
		}else{
			System.out.println("分数的值属于正确范围...");
		}
	}
}

11.异常的注意事项:
  1)子类在重写父类中的方法的时候,如果父类中方法有抛出异常,那么子类重写的这个方法,
  抛出异常不能够比父类中该方法异常大,(要么是父类中该方法异常的子类)(最起码应该保存一致)(父亲坏了,儿子不能比父亲更坏)
  2)子类继承父类,要重写父类中的方法的时候,如果本身父类中该方法没有异常,那么在子类中重写该方法的时候,不能抛出异常,只能捕获异常!
例子:

public class ExceptionDemo {

}

class Fu{
	//父类中带有抛出异常的方法
	public void show() throws Exception{
		
	}
	
	public void method(){}
}


class Zi extends Fu{
	@Override
	public void show() throws Exception{}
	
	@Override
	public void method(){
		String str = "2017-10-19" ;
		
		//创建SimpleDateFormat对象
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") ;
		try {
			Date d = sdf.parse(str) ;
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}
}

二.File类

    1.IO流之前要先懂得如何封装硬盘上的以文件或者目录,使用File类
       File,是用来描述文件或者目录(文件夹)的路径的抽象表现形式
  
  
  常用的构造方法:
public File(String pathname):给定路径名以字符串来表示当前这个文件或者文件夹(开发中推荐使用第一种                   构造方法)
   public File(String parent,String child)根据 parent 路径名字符串和 child 路径名字符串创建一个新 File对象 
   public File(File parent, String child)根据 parent 抽象路径名和 child 路径名字符串创建一个新 File 实例
  需求:要表示当前计算机e盘下一个demo文件夹中的一个a.txt文件

public class FileDemo {
	
	public static void main(String[] args) {
		
		//创建一个File实例
		//方式1
		File file = new File("E:\\demo\\a.txt") ;
		System.out.println(file);
		
		//方式2
		File file2 = new File("E:\\demo", "a.txt") ;
		System.out.println(file2);
		
		//方式3
		File file3 = new File("E:\\demo") ;
		File file4 = new File(file3, "a.txt") ;
		System.out.println(file4);
	}
}


2.使用File对象可以创建文件或者文件夹
   里面跟创建有关的成员方法:
   public boolean mkdir()创建此抽象路径名指定的目录(文件夹)。
   如果当前某个盘符下已经有了这个目录(文件夹),不会在创建了.
   public boolean createNewFile():创建文件的,如果已经有这个文件了,不在创建,并且该方法本身就会编译时期                异常IOException
                      throws IOException
        public boolean mkdirs()创建此抽象路径名指定的目录,包括所有必需但不存在的父目录。(创建文件夹,文件夹不         存在,才开始创建)
        
        注意事项:
        自己要清楚要创建的是文件夹还是文件,每个方法都不一样!
       
        没有带盘符,默认到当前项目下创建文件或者文件夹..

例子:

public class FileDemo {
	
	public static void main(String[] args) throws IOException {
		
		//需要在E盘下创建一个新的文件夹:demo
		//描述一下这个文件的抽象路径形式
		//用File对象来封装当前这个文件夹
		File file = new File("e:\\demo") ;
		//创建文件夹
		System.out.println("mkdir:"+file.mkdir());
		
		//public boolean createNewFile():创建文件:在E盘下的demo文件夹中创建a.xt文件
		File file2 = new File("E:\\demo\\a.txt") ;
		System.out.println("createNewFile:"+file2.createNewFile());
		
		//需求:在E盘下的test文件夹下创建一个b.txt文件
//		File file3 = new File("e:\\test\\b.txt") ;//创建文件之前,确保当前盘符下有这个文件夹,否则,IOEXception:系统找不到指定路径
//		System.out.println("createNewFile:"+file3.createNewFile());
		
		
		//public boolean mkdirs()
	//需求:在e盘下创建aaa文件夹,在创建子目录bbb--->ccc--ddd
		
		//创建File对象来封装
		File file4 = new File("E:\\aaa\\bbb\\ccc\\ddd") ;
		//public boolean mkdirs()
		System.out.println("mkdirs:"+file4.mkdirs());
		
		没有带盘符,默认到当前项目下创建了文件
		File file5 = new File("a.txt") ; 
		System.out.println("createNewFile:"+file5.createNewFile());
		
	}
}
如果不小心创建文件或者文件夹的时候,没有写盘符那么就会当前项目下进行创建

  3.删除

  public boolean delete()删除此抽象路径名表示的文件或目录

   删除不能删除带有文件或者文件夹的目录
  
   注意事项:
   删除的方法不能删除带有目录或者文件的文件夹
   删除多个目录,必须逐一删除!

例子:

public class FileDemo {
	
	public static void main(String[] args) {
		
		//在当前项目下创建aaa\\bbb\\ccc
		File file = new File("aaa\\bbb\\ccc") ;
		System.out.println("mkdirs:"+file.mkdirs());
		
		//需求:要删除当前项目下的a.txt文件
		File file2 = new File("a.txt") ;
		System.out.println("delete:"+file2.delete());
		
		//需求:删除aaa\\bbb\\ccc
		File file3 = new File("aaa\\bbb\\ccc") ;
		System.out.println("delte:"+file3.delete());
		
		File file4 = new File("aaa\\bbb") ;
		System.out.println(file4.delete());
		
		File file5 = new File("aaa") ;
		System.out.println(file5.delete());
	}
}

4.重命名

File类中的重命名功能:
   public boolean renameTo(File dest)重新命名此抽象路径名表示的文件。 
  
   1)使用这个功能:当两个抽象路径一致,那么只是重命名
   2)当这两个抽象路径不一致,有剪切并且改名了...

public class FileDemo2 {
	
	public static void main(String[] args) {
		
		//现在要描述当前项目下有一个高圆圆.jpg 
		File file = new File("高圆圆.jpg") ;
		
		//使用重命名功能:文件名称该成:杨桃.jpg
		File file2 = new File("杨桃.jpg") ;
		
		//调用功能
		file.renameTo(file2) ;
		
		//需求:将当前项目下的杨桃.jpg--->复制到e:\\高圆圆.jpg
		File file3 = new File("杨桃.jpg") ;
		
		//E:\\高圆圆.jpg
		File file4 = new File("E:\\高圆圆.jpg") ;
		file3.renameTo(file4) ;
	}
}
5.判断功能

File类中的判断功能:
  public boolean isDirectory():判断是否是文件夹经常用到
  public boolean isFile():判断是否是一个标准文件经常用到
  public boolean canRead():判断是否可读
  public boolean canWriter():判断是否可写
  public boolean isHidden():判断是否是隐藏文件
public boolean isAbsolute():判断次路径名是否是绝对路径

public class FileDemo {
	
	public static void main(String[] args) throws IOException {
		
		//在当前项目下创建一个文件
		File file = new File("a.txt") ;
		//System.out.println(file.createNewFile());
		
		System.out.println(file.isDirectory());
		System.out.println(file.isFile());
		System.out.println(file.canRead());
		System.out.println(file.canWrite());
		System.out.println(file.isHidden());
		System.out.println(file.isAbsolute());
	}
}

6.获取功能

File类中的获取功能:
  public File getAbsolutePath():获取当前文件或者文件夹绝对路径
   public String getPath():获取相对路径
   public long length()返回由此抽象路径名表示的文件的长度
  public long lastModified()返回此抽象路径名表示的文件最后一次被修改的时间
public String getName():获取名称

例子:

public class FileDemo2 {

		public static void main(String[] args) {
			File file = new File("a.txt") ;
			
			//绝对路径
			System.out.println(file.getAbsolutePath());//E:\javacode\workspace\day17_File\a.txt
			//相对路径
			System.out.println(file.getPath());//a.txt
			System.out.println(file.getName());
			
			System.out.println(file.length());//描述文件内容 长度
			System.out.println(file.lastModified());//1511075302018	long:时间毫秒值
			
			//long---->Date---->String"日期文本格式"
			//创建日期对象
			Date d = new Date(1511075302018L) ;
			//创建一个SimpleDateFormat对象
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") ;
			
			//格式化
			String dateStr = sdf.format(d) ;
			System.out.println(dateStr);//2017-11-19 15:08:22
			
			
		}
}

7.File类的高级获取功能:
   public String[] list():返回对象是一个字符串数组,当前哪个一盘符下的所有的文件以及文件夹的字符串名称数组
   public File[] listFiles():返回对象是一个File数组,当前哪个盘下的所有的文件以及文件夹的File数组

例子:

public class FileDemo {
	
	public static void main(String[] args) {
		//需求:获取e盘下所有的文件夹以及文件的字符串名称数组

		//用File对象封装下e盘
		File file = new File("E:\\") ;
		
				public String[] list()
		String[] strArray = file.list() ;
		//遍历:遍历之前,一定要做非空判断
		if(strArray!=null){
			//增强for遍历
			for(String s:strArray){
				System.out.println(s);
			}
		}
		
		System.out.println("------------------------------------------");
		//public File[] listFiles():
		File[] fileArray = file.listFiles() ;
		if(fileArray !=null){
			for(File f :fileArray){
				System.out.println(f.getName());
			}
		}
		
	}
}

三.io

1.IO流:设备和设备之间的数据传输
   设备和设备指的是:硬盘和内存之间的数据传输
  
 2. IO流的分类:
   按流的方向分:
   输入流:读数据的
   输出流:写数据的
  按数据类型分:
   字节流:
   字节输入流:InputStream
   字节输出流:OutputStream
字符流
   字符输入流:Reader
   字符输出流:Writer
  
  需求:输出一个文本文件,给文本文件中写一句话:hello,IO,Im'coming...
  
  分析:
   一旦提到文本文件,那么就是用字符流,但是字符流是在字节流之后出现的,所以先学习字节流!
   用windows自带的记事本打开一个文件,你自己看懂,一般情况使用字符流最好.如果打开之后,读不懂,那么使用字节流.
   使用字节流,来输出这个文件
   OutputStream:字节输出流,该类是抽象类,不能实例化,但是这里提到文件,刚才学习的File类就是描述文件的.
   FileOutputStream:OutputStream的子类
   构造方法:
   public FileOutputStream(String name)
   在抽象类的前面加上前缀:
   XXXInputStream
   XXXOutputStream
   XXXReader
   XXXWriter
   FileInputStream
   FileReader
   FileWriter
  
  开发步骤"
  1)创建文件输出流对象
  2)写数据
  3)关闭资源

代码如下:

public class OutputStreamDemo {
	
	public static void main(String[] args) throws IOException {
		//创建输出流对象
//		OutputStream os = new FileOutputStream("os.txt") ;//抽象类多态
		
		FileOutputStream fos = new FileOutputStream("fos.txt") ;
		
		/**
		 * 创建文件输出流对象做了哪些事情:
		 * 	Java语言不能创建系统资源,通过C或C++间接创建系统资源
		 * 	创建的这个输出流对象,并指向这个fos.txt文件进行输出.
		 */
		
		//有对象了,写数据
		//String类中一个方法:
				//getBytes() ;
		fos.write("hello,io,i'm coming...".getBytes()) ;
		
		//释放流资源
		fos.close() ;
		/**
		 * 关闭流资源,关闭了就不能在写数据了
		 * 并且该流对象输出完毕之后,不指向这个文件了,所以需要将它关闭掉
		 */
		
		//java.io.IOException: Stream Closed:流已经关闭了,不能在操作了!
//		fos.write("高圆圆".getBytes()) ;
	}
}

3.针对输出流中写数据的方法:
   public abstract void write(int b):将指定的字节写入到输出流中
public void write(byte[] b):将指定的字节数组写入到输出流中
   public void write(byte[] b, int off,int len):将字节数组的一部分写入到输出流中

例子:

public class FileOutputStreamDemo {
	
	public static void main(String[] args) throws IOException {
		
		//创建一个文件输出流对象
		FileOutputStream fos = new FileOutputStream("fos2.txt") ;
		
		//写数据
		//		public abstract void write(int b):将指定的字节写入到输出流中
//		fos.write(97) ;//---->二进制数据----->记事本打开--->就找会找ASCII码表中找有没有该值对应的一个字符: a
//		fos.write(55) ;
//		fos.write(57) ;
//		fos.write(65) ;
		
		//public void write(byte[] b):将指定的字节数组写入到输出流中
		byte[] bys = {97,98,99,100,101} ;
		fos.write(bys) ;
		
		//public void write(byte[] b, int off,int len):实际开发中:该方法和读数据一块使用
		fos.write(bys, 1, 3) ;
		
		//关闭资源
		fos.close() ;
	}
}

4.换行

写入了这个数据,发现数据和数据之间没有换行?
  
   需要写入换行符号,每一个系统他们对应IO这块换行符号是不一样的
   对于windows操作系统来说:换行符号:\r\n
   对于Linux操操作系统来说:\n
  对于Mac操作系统来说:\r
  
  如何给这个文件追加写入数据呢?
   public FileOutputStream(File file,boolean append):第二个参数设置为true,表示写入文件的末尾处


例子:

public class FileOutputStreamDemo2 {
	
	public static void main(String[] args) throws IOException {
		
		//创建一个输出流对象
		FileOutputStream fos = new FileOutputStream("fos3.txt",true) ;
		
		//写数据
		for(int x = 0 ; x <10 ; x ++){
			fos.write(("helo"+x).getBytes()) ;
			//写入一个换行符号
			fos.write("\r\n".getBytes());
		}
		
		
		//关闭资源
		fos.close() ;
	}
}

5.IO流中加入异常操作

例子:

public class FileOutputStreamDemo3 {

		public static void main(String[] args) {
			//方式1:
			//分别try...catch...
			//创建文件输出流对象
		/*	FileOutputStream fos = null ;
			try {
				fos = new FileOutputStream("fos4.txt")  ;
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
			
			
			//写数据
			try {
				fos.write("java".getBytes()) ;
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			//释放资源
			try {
				fos.close() ;
			} catch (IOException e) {
				e.printStackTrace();
			}
			*/
			
			/*方式2:放在一块try...catch...
			try {
				//分别try...cacth笔记麻烦,
				FileOutputStream fos = new FileOutputStream("fos4.txt") ;
				//写数据
				fos.write("hello,java".getBytes()) ;
				//释放资源
				fos.close() ;
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}*/
			
			//方式3:加入标准格式:try...catch...finally
			//IO流中加入异常操作的标准用法:
			//声明一个变量
			FileOutputStream fos = null ;
			
			try {
				fos = new FileOutputStream("fos4.txt") ;
				
				//写数据
				fos.write("hello,Javaweb".getBytes()) ;
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}finally{
				//释放资源的
				//由于是流对象,要对流对象做非空判断
				if(fos !=null){
					try {
						fos.close() ;
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值