文件与IO流

文件与IO流

1.  File类

 FIle类可以实现文件的,创建,删除,重命名,获取路径,创建时间....

  是唯一与文件本身有关的操作类

    构造方法:

  new File(文件的路径);

 

  属性:

 separator  静态属性=\

 

  方法:

 exists()  判断文件是否存在

 createNewFile()   创建文件

 getAbsolutePath()  文件的绝对路径

 String类的方法   endsWith("txt")  判断文件的后缀名是否是 我们想要的

 lastModified()   获取文件最后修改的时间

 length()    文件的长度

 isDirectory()   是否为目录

 mkdir() 创建目录

 delete()  删除文件

 file2.list()  获取某个目录下的文件名             String []

 file2.listFiles()  获取某个目录下的文件    File []

 publicstatic void main(String[] args) {

                   //TODO Auto-generated method stub

                   //实例化文件对象 【指向的文集或目录不一定存在】

                   Filefile=new File("E:\\a.txt");

                   //Filefile1=new File("E:/a.txt");

                   //File.separator代表 \

                   //Filefile2=new File("E:"+File.separator+"a.txt");

                  

                   System.out.println("文件是否存在:"+file.exists());

                                    

                   //创建

                   if(!file.exists()){//判断不存在

                            try{

                                     file.createNewFile(); //创建文件

                            }catch (IOException e) {

                                     //TODO Auto-generated catch block

                                     e.printStackTrace();

                            }

                   }
                        

                   //获得文件的路径

                   Stringpath=file.getAbsolutePath();

                   System.out.println("文件的绝对路径是:"+path);

                                    

                   //判断文件的后缀名是否是 我们想要的

                   System.out.println("该路径对应的文件是否是txt文件:"+path.endsWith("txt"));

                  

                   //获取文件最后修改的时间

                   longlastModified=file.lastModified();

                   System.out.println("最后修改的时间是:"+lastModified);

                   //给返回的秒做格式化

                   SimpleDateFormatsdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                   StringlastTime=sdf.format(new Date(lastModified));

                   System.out.println("最后修改的时间是:"+lastTime);

                                    

                   //获取文件的长度

                   System.out.println("文件的长度是:"+file.length()+"字节");

                                    

                   //判断是否为目录

                   System.out.println("是否为目录:"+file.isDirectory());

                                    
                   //------------------------------------------------------------

                   //创建目录

                   File file2=new File("E:\\NIIT");

                   if(!file2.isDirectory()){//判断目录是否存在

                            file2.mkdir();  //创建目录

                   }

                                    
                   //删除

                   //file2.delete();

                                    

                   //获取某个目录下的文件名

                   String[] names=file2.list();

                   for(Stringname : names){

                            System.out.println(name);

                   }
                

                   //获取某个目录下的所有文件

                   File[] fils=file2.listFiles();

                   for(Filef : fils){

                            System.out.println(f.getPath()+"\t"+f.length());

                   }

2. IO 流 : 输入流/输出流(input/output) 将物理文件读取到程序中/将程序中的数据写到物理文件当中

          

           IO流分类 1.根据不同的数据类型:字节流,字符流

                   2.根据不同的流向划分:输出流, 输入流

                    

           以程序作为参照 输入流 read 输出流 writer

 

 字节的输出流

           OutPutStream抽象类是所有输出字节流的父类,一般我们使用FileOutPutStream进行字节流的输出 1.实例化字节输出流

                   2.写出去

3.关闭流           

publicstatic void outPutStream() {

                   OutputStreamfos = null;

                   //实例化文件类

                   Filef = new File("E:\\a.txt");

                   try{

                            //实例化字节输出流的类

                            fos= new FileOutputStream(f); // true告诉字节输出流 里面的数据做追加

                            Stringname = "我为什么,这么帅";

                            //把字符串转成字节数组

                            byte[]b = name.getBytes();

                            //把字节数组的数据写入字节输入流

                            fos.write(b);

                   }catch (FileNotFoundException e) {

                            //TODO Auto-generated catch block

                            e.printStackTrace();

                   }catch (IOException e) {

                            //TODO Auto-generated catch block

                            e.printStackTrace();

                   }finally {

                            try{

                                     //关闭输出流

                                     fos.close();

                            }catch (IOException e) {

                                     //TODO Auto-generated catch block

                                     e.printStackTrace();

                            }

                   }

         }


字节的输入流

InputStram抽象类是所有字节输入流的父类 一般我们使用FileInputStream进行字节的输入

           1.创建字节输入流 2.读取 3.关闭  

publicstatic void inputoutStreams() {

                   FileInputStreamfis = null;

                   Filef = new File("E:\\a.txt");

                   try{

                            //实例化字节输入流

                            fis= new FileInputStream(f);

                            //读

                            //创建一个字节数组用来存放读取到的字节

                            byte[]b = new byte[1024  1024  10]; // 1kb=1024字节10241024=1MB

                            //byte [] b=new byte[2];

                            //读取字符的累加

                            StringBuffersb = new StringBuffer();

                            //记录每次读取的长度

                            intlen = 0;

                            while((len = fis.read(b)) != -1) { // read(byte [] b)

                              //每次最多读取b.length的长度返回读取有效字节的长度

                                     sb.append(newString(b, 0, len));

                            }

                            //字符串输出

                            System.out.println(sb.toString());

                   }catch (FileNotFoundException e) {

                            //TODO Auto-generated catch block

                            e.printStackTrace();

                   }catch (IOException e) {

                            //TODO Auto-generated catch block

                            e.printStackTrace();

                   }finally {

                            try{

                                     fis.close();//关闭字节输入流

                            }catch (IOException e) {

                                     //TODO Auto-generated catch block

                                     e.printStackTrace();

                            }

                   }

         }

字符的输出流

           Writer写入字符流的抽象类,子类必须实现的方法仅有writer(char[],int i)  flush();  close();

           一般我们使用Filewriter进行字符的输出

          

           1.创建字符的输出流

           3.写

           3.关闭流

 字符的输出流每次写入 会进入一定的缓存  必须手动调用flush(); 清空缓存

 如果没有手动调用flush();在流close() 会默认清空缓存。       

publicstatic void fileWriter(){

                   //实例化文件类

                   Filef=new File("E:\\a.txt");

                   //创建字符输出流

                  FileWriter fw=null;

                   try{

                            //实例化字符输出流

                            fw=newFileWriter(f,true);

                            //写

                            Stringname="我为什么,这么帅";

                           

                            //调用write写入

                            fw.write(name);

                            fw.write("\r\n");

                            fw.flush();

                   }catch (IOException e) {

                            //TODO Auto-generated catch block

                            e.printStackTrace();

                   }finally{

                            try{

                                     fw.close();//关闭字符输出流

                            }catch (IOException e) {

                                     //TODO Auto-generated catch block

                                     e.printStackTrace();

                            }

                   }

         }

           字符的输入流

           Reader用于读取字符流的抽象类,子类必须实现的方法有reade(char [],int i)   close();

           一般我们使用FileReader类进行字符的输入

          

           1.创建字符的输入类

           2.读

           3.关闭流

publicstatic void fileRead(){

                   Filef=new File("E:\\a.txt");

                   FileReaderfr=null;

                   try{

                            //实例化字符输入类

                            fr=newFileReader(f);

                            //读

                            char[] c=new char[2];

                            //记录每次读取字符的有效长度

                            intlen=0;

                            //追加

                            StringBuffersb=new StringBuffer();

                            while((len=fr.read(c))!=-1){

                                     sb.append(newString(c, 0, len));

                            }

                            //输出字符串

                            System.out.println(sb.toString());

                   }catch (FileNotFoundException e) {

                            //TODO Auto-generated catch block

                            e.printStackTrace();

                   }catch (IOException e) {

                            //TODO Auto-generated catch block

                            e.printStackTrace();

                   }finally{

                            try{

                                     fr.close();//关闭流

                            }catch (IOException e) {

                                     //TODO Auto-generated catch block

                                     e.printStackTrace();

                            }

                   }

         }

3. 缓存流

字节的缓存流

           为什么使用缓冲流:

           对文件频繁的操作,效率低,性能差。

          

           使用缓冲流:能够高效的读写信息,原理:将数据先缓冲起来,然后一起写入或读出

字节输出的缓冲流BufferedOutputStream

  publicstatic void outPutStream() {

                   FileOutputStreamfos = null;

                   BufferedOutputStreambos=null;
 

                   //实例化文件类

                   Filef = new File("E:\\a.txt");

                   try{

                            //实例化字节输出流的类

                            fos= new FileOutputStream(f);

                            bos=newBufferedOutputStream(fos); //实例化缓冲流

                            Stringname = "我为什么,这么帅";

                            //把字符串转成字节数组

                            byte[]b = name.getBytes();

                            //把字节数组的数据写入字节输入流

                            bos.write(b);

                   }catch (FileNotFoundException e) {

                            //TODO Auto-generated catch block

                            e.printStackTrace();

                   }catch (IOException e) {

                            //TODO Auto-generated catch block

                            e.printStackTrace();

                   }finally {

                            try{

                                     //关闭输出流

                                     bos.close();

                                     fos.close();                   

                            }catch (IOException e) {

                                     //TODO Auto-generated catch block

                                     e.printStackTrace();

                            }

                   }

         }

        字节的输入缓冲流

  //BufferedInputStream

         publicstatic void inputoutStreams() {

                   FileInputStreamfis = null;

                   BufferedInputStreambis=null;

                   Filef = new File("E:\\a.txt");

                   try{

                            //实例化字节输入流

                            fis= new FileInputStream(f);

                            bis=newBufferedInputStream(fis);//实例化字节的缓冲流

                            //读

                            //创建一个字节数组用来存放读取到的字节

                            byte[]b = new byte[1024  1024  10]; // 1kb=1024字节10241024=1MB

                            //byte [] b=new byte[2];

                            //读取字符的累加

                            StringBuffersb = new StringBuffer();

                            //记录每次读取的长度

                            intlen = 0;

                            while((len = fis.read(b)) != -1) { // read(byte [] b)

                                  //每次最多读取b.length的长度返回读取有效字节的长度

                                     sb.append(newString(b, 0, len));

                            }

                            //字符串输出

                            System.out.println(sb.toString());

                   }catch (FileNotFoundException e) {

                            //TODO Auto-generated catch block

                            e.printStackTrace();

                   }catch (IOException e) {

                            //TODO Auto-generated catch block

                            e.printStackTrace();

                   }finally {

                            try{

                                     bis.close();

                                     fis.close();//关闭字节输入流

                            }catch (IOException e) {

                                     //TODO Auto-generated catch block

                                     e.printStackTrace();

                            }

                   }

         }

字符的缓冲流BufferedWriter

public static void fileWriter(){

                   //实例化文件类

                   Filef=new File("E:\\a.txt");

                   //创建字符输出流

                   FileWriterfw=null;

                   BufferedWriterbw=null;

                   try{

                            //实例化字符输出流

                            fw=newFileWriter(f,true);

                            bw=newBufferedWriter(fw);//实例化字符缓冲流

                            //写

                            Stringname="我为什么,这么帅";

                           

                            //调用write写入

                            bw.write(name);

                            //fw.write("\r\n");

                            bw.newLine();

                            bw.write(name);

                            bw.flush();

                   }catch (IOException e) {

                            //TODO Auto-generated catch block

                            e.printStackTrace();

                   }finally{

                            try{bw.close();

                                     fw.close();//关闭字符输出流

                            }catch (IOException e) {

                                     //TODO Auto-generated catch block

                                     e.printStackTrace();

                            }

                   }

         }

 字符的缓冲输入流BufferedReader

  public static voidfileRead(){

                   Filef=new File("E:\\a.txt");

                   FileReaderfr=null;

                   BufferedReaderbr=null;

                   try{

                            //实例化字符输入类

                            fr=newFileReader(f);

                            br=newBufferedReader(fr); //实例化字符缓冲流

                         //读

                         char[] c=new char[2];

                         //记录每次读取字符的有效长度

                         intlen=0;

                         //追加

                         StringBuffersb=new StringBuffer();

                         while((len=br.read(c))!=-1){

                                  sb.append(newString(c, 0, len));

                         }

                         //输出字符串

                         System.out.println(sb.toString());

                            Stringstr="";

                            while((str=br.readLine())!=null){

                                     System.out.println(str);

                            }

                   }catch (FileNotFoundException e) {

                            //TODO Auto-generated catch block

                            e.printStackTrace();

                   }catch (IOException e) {

                            //TODO Auto-generated catch block

                            e.printStackTrace();

                   }finally{

                            try{

                                     br.close();

                                     fr.close();//关闭流

                            }catch (IOException e) {

                                     //TODO Auto-generated catch block

                                     e.printStackTrace();

                            }

                   }

         }

4. 对象流

          * 序列化          将对象保存为文件【ObjectOutputStream】

          * 反序列化     将文件恢复成对象【ObjectInputStream】

          *

          * 注意点:被序列化的对象所在的类 必须实现java.io.Serializable接口

          //    privatetransient double money;  //被transient修饰的属性不能被序列化

          */

         publicstatic void main(String[] args) {

                   //TODO Auto-generated method stub

                   //ObjectOut();

                   ObjectInput();

         }

         //序列化

public static void ObjectOut(){
		File file=new File("E:\\Student");
		
		FileOutputStream out=null;
		ObjectOutputStream oos=null;//创建序列化对象
		try {
			out=new FileOutputStream(file);
			oos=new ObjectOutputStream(out);//实例化序列化对象
			//写一个对象
			//Student lsd=new Student(1, "刘升东", 18, 10); //创建学生对象
			//oos.writeObject(lsd); //把对象写入文件
			
			//写一个对象数组
			Student [] stu={new Student(1, "刘升东", 18, 10),new Student(2, "刘升西", 19, 10),new Student(3, "刘升南", 20, 10),new Student(4, "刘升北", 21, 10)};
			oos.writeObject(stu);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				oos.close();
				out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

         //反序列化

public static void ObjectInput(){
		File file=new File("E:\\Student");
		FileInputStream in=null;
		ObjectInputStream ios=null;//创建反序列化对象
		try {
			in=new FileInputStream(file);
			ios=new ObjectInputStream(in);//实例化反序列化对象
			
//			Student lsd=(Student) ios.readObject();//读取文件【一个对象】    转换为对象类型
//			System.out.println(lsd.getId()+"\t"+lsd.getName()+"\t"+lsd.getAge()+"\t"+lsd.getMoney());
			
			Student [] stu=(Student[]) ios.readObject();
			for(Student lsd : stu){
				System.out.println(lsd.getId()+"\t"+lsd.getName()+"\t"+lsd.getAge()+"\t"+lsd.getMoney());
			}
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

5. 打印流

          * 打印流的主要功能用于输出【写】 在整个Io包中打印流分成两种类型

          * 字节打印流  PrintStram

          *

          * 字符打印流 PrintWriter

          *

          */

         publicstatic void main(String[] args) {

                   //printStream();

                   printWriter();

         }

        

         //打印字节流

public static void printStream(){
		File f=new File("E:\\a.txt");
		FileOutputStream fos=null;
		BufferedOutputStream bos=null;
		PrintStream ps=null;//创建打印字节流
		try {
			fos=new FileOutputStream(f);
			bos=new BufferedOutputStream(fos);
			
			ps=new PrintStream(bos);//实例化打印字节流
			ps.println("我为什么这么骚气");//打印
			ps.print(true);
			ps.print(666);
			
//			String name="我为什么这么骚";
//			bos.write(name.getBytes());
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				ps.close();//关闭流
				bos.close();
				fos.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

         //打印字符流

public static void printWriter(){
		File f=new File("E:\\a.txt");
		FileWriter fw=null;
		BufferedWriter bw=null;
		PrintWriter pw=null;
		try {
			fw=new FileWriter(f);
			bw=new BufferedWriter(fw);
			
			pw=new PrintWriter(bw);
			pw.print("666");
			pw.println("999");
			pw.print(000);
			
			
			
			
//			bw.write("我为什么什么穷");
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				pw.close();
				bw.close();
				fw.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

6. RandomAccessFile

 * 是io包下的类   从Object直接继承下来的   只可以对文件进行操作    可以读取和写入

 * 他的功能在jdk1.4后被new io【NIO】给几乎取代

 

7. 常见的字符编码

          *ISO8859-1:编码属于单字节编码,最多只能表示0-255的字节范围,主要用与英文

          * GBK/GBK2312:中文的国际编码,专门用于表示汉字,是双字节编码

          * Unicode:java中就是使用此编码方式,也是最标准的一种16【占用的空间多/对英文字母也需要两个字节】进制表示的编码,此编码不能兼容ISO8859-1;

          * UTF:兼容ISO8859-1,用来表示所有的语言字符,uft是不定长的编码,因为每个字符的长度从1-6个字节不等,一般中文外文交互的网站使用

          *

          *

          * 应用场景【出现乱码的原因】;

          * 程序使用的编码与本机的编码不统一

          * 网络中,客户端与服务器端的编码不一致

 

8.New Io

          *

          * 为什么使用New IO

          * NIO可以实现高速的文件读取。无须定义本机代码。NIO将最耗时的IO流操作【填充/提取缓冲区】转移给操作系统。因而提高了速度

          *

          * NIO与Io的区别

          * NIO以块的方式处理数据的【每一个操作都在一步中产生或消耗】

          * IO以流的方式来处理数据【输入流产生一个字节数据,输出流消耗一个字节数据】

          *

          * 缓冲区

          * 在NIO包中的类,

          * NIO中的所有数据都由缓冲区处理的,在读取数据时,他都是直接读到缓冲取值的,写入数据时他都是写入到缓冲区的,

          * 任何时候访问NIO中的数据,都是在缓冲区中的

          *

          * 什么是缓冲区【定义】

          * 实际上是一个数组,通常的情况下是一个字节数组【ByteBuffer】,并不是NIO流中惟一的缓冲区

          * CharBuffer   ShortBuffer  IntBuffer  LongBuffer FloaftBuffer   DoubleBuffer

          *

          *

          */

       

public static void main(String[] args) {
		// TODO Auto-generated method stub
		//使用1
		//创建了一个10个字节缓冲区
		ByteBuffer bb=ByteBuffer.allocate(10);
		
		System.out.println("当前位置:"+bb.position()); //0
		System.out.println("限制位置:"+bb.limit());    //10
		
		bb.put((byte)10);
		byte [] b={20,30,40};
		bb.put(b);
		bb.flip();//反转
		
		System.out.println("当前位置:"+bb.position());//
		System.out.println("限制位置:"+bb.limit());  //4
		
		for(int i=0;i<bb.remaining();i++){//remaining返回当前位置到限制位置之间的元素个数
			System.out.println(bb.get(i));
		}
		
	}

9. 通道【Channel

          * Channel是一个对象,可以通过他读取和写入数据,   拿io比较 就相当于流

          * NIO所有的数据是通过BUFFER【缓冲】对象来处理的。永远不会将字节写入通道,相反试讲数据写入缓冲区

          * 同样也会将数据直接冲通道读取,而是从缓冲区读取

          */

public static void main(String[] args) {
		// TODO Auto-generated method stub
		FileInputStream fis=null;
		FileOutputStream fos=null;
		FileChannel fcin=null;
		FileChannel fcout=null;
		
		try {
			fis=new FileInputStream("E:\\ao.png");
			fos=new FileOutputStream("D:\\po.png");
			
			//获取读得通道  输入流通道
			fcin=fis.getChannel();
			//获取写的通道  输出流的通道
			fcout=fos.getChannel();
			
			//创建字节缓冲区    其大小为图片总大小
			ByteBuffer bb=ByteBuffer.allocate(fis.available());
			
			//读缓冲区
			fcin.read(bb);
			//反转
			bb.flip();
			//写入缓冲
			fcout.write(bb);
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				fcout.close();
				fcin.close();
				fos.close();
				fis.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值