Week04_day02 IO流(上) File和字节流

来源:互联网 发布:有没有淘宝卖家骗货 编辑:程序博客网 时间:2024/06/03 17:50

File类

File类描述的是一个文件或文件夹。(文件夹也可以称为目录)

该类的出现是对文件系统的中的文件以及文件夹进行对象的封装。可以通过对象的思想来操作文件以及文件夹。

可以用面向对象的处理问题,通过该对象的方法,可以得到文件或文件夹的信息方便了对文件与文件夹的属性信息进行操作。

文件包含很多的信息:如文件名、创建修改时间、大小、可读可写属性等。

构造方法:

创建File对象需要导包,    importjava.io.File 

new File(String pathname);

       通过将给定路径来创建一个新File实例。

new File(String parent, String child);

       根据parent路径名字符串和child路径名创建一个新File实例。

         parent是指上级目录的路径,完整的路径为parent+child.

new File(File parent, String child);

       根据parent抽象路径名和child路径名创建一个新File实例。

       parent是指上级目录的路径,完整的路径为parent.getPath()+child.

说明:

      如果指定的路径不存在(没有这个文件或是文件夹),不会抛异常,这时file.exists()返回false。

 File类中常用的方法:

   创建:

   createNewFile() 在指定位置创建一个空文件,成功就返回true,如果已存在就不创建然后返回false

      mkdir()         在指定位置创建目录,这只会创建最后一级目录,如果上级目录不存在就抛异常。

      mkdirs()     在指定位置创建目录,这会创建路径中所有不存在的目录。

      renameTo(File dest)   重命名文件或文件夹,也可以操作非空的文件夹,文件不同时相当于文件的剪切,剪切时候不能操作非空的文件夹。移动/重命名成功则返回true,失败则返回false。

 

  

   删除:

delete()     删除文件或一个空文件夹,如果是文件夹且不为空,则不能删除,成功返回true,失败返回false。

deleteOnExit()  在虚拟机终止时,请求删除此抽象路径名表示的文件或目录,保证程序异常时创建的临时文件也可以被删除

 

     

   判断:

exists()     文件或文件夹是否存在。

isFile()     是否是一个文件,如果不存在,则始终为false。

isDirectory()   是否是一个目录,如果不存在,则始终为false。

isHidden()      是否是一个隐藏的文件或是否是隐藏的目录。

isAbsolute() 测试此抽象路径名是否为绝对路径名。

 

     

   获取:

getName()    获取文件或文件夹的名称,不包含上级路径。

getPath()       返回绝对路径,可以是相对路径,但是目录要指定

getAbsolutePath()  获取文件的绝对路径,与文件是否存在没关系

length()     获取文件的大小(字节数),如果文件不存在则返回0L,如果是文件夹也返回0L。

getParent()     返回此抽象路径名父目录的路径名字符串;如果此路径名没有指定父目录,则返回null。

lastModified()  获取最后一次被修改的时间。

   文件夹相关:

staic File[] listRoots() 列出所有的根目录(Window中就是所有系统的盘符)

list()                返回目录下的文件或者目录名,包含隐藏文件。对于文件这样操作会返回null。

list(FilenameFilter filter)  返回指定当前目录中符合过滤条件的子文件或子目录。对于文件这样操作会返回null。

listFiles()              返回目录下的文件或者目录对象(File类实例),包含隐藏文件。对于文件这样操作会返回null。

listFiles(FilenameFilter filter)   返回指定当前目录中符合过滤条件的子文件或子目录。对于文件这样操作会返回null。

IO流的分类

   流按操作数据类型的不同分为两种:字节流与字符流。

   流按流向分为:输入流,输出流(以程序为参照物,输入到程序,或是从程序输出)

什么是字节流

我们已经知道File对象封装的是文件或者路径属性,但是不包含向(从)文件读(写)数据的方法。为了实现对文件的读和写操作需要学会正确的使用Java的IO创建对象。

字节流的抽象基类:

   输入流:java.io.InputStream

   输出流:java.io.OutputStream

特点:

      字节流的抽象基类派生出来的子类名称都是以其父类名作为子类名的后缀。

      如:FileInputStream, ByteArrayInputStream等。

说明:

      字节流处理的单元是一个字节,用于操作二进制文件(计算机中所有文件都是二进制文件)

输入流:InputStream -> FileInputStream

package com.serendipity.io;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;/** * 编码: * GBK:识别大部分中文。 1个中文占两个字节   1个字母或者数字 占1个 * utf-8:基本涵盖了所有中文   1个汉字占3个字节   1个字母或者数字 占1个 * iso8859-1:绝对不识别中文。  老外用的  英语 *  *  * 字节输入流 * InputStream:抽象类 * FileInputStream  字节输入流 *  *  * FileInputStream: * FileInputStream(File file)           通过打开一个到实际文件的连接来创建一个 FileInputStream,该文件通过文件系统中的 File 对象 file 指定。 * FileInputStream(String name)           通过打开一个到实际文件的连接来创建一个 FileInputStream,该文件通过文件系统中的路径名 name 指定。                int read()           从此输入流中读取一个数据字节。  int read(byte[] b)           从此输入流中将最多 b.length 个字节的数据读入一个 byte 数组中。  int read(byte[] b, int off, int len)           从此输入流中将最多 len 个字节的数据读入一个 byte 数组中。  void close()           关闭此文件输入流并释放与此流有关的所有系统资源。                                 缓冲数组:值一般是1024或者是1024的整数倍     值越大  效率越大               int available()           返回此输入流下一个方法调用可以不受阻塞地从此输入流读取(或跳过)的估计字节数。            * @author tomcat * *//** * 缓冲数组读取文本  抓 * @author tomcat * */public class DemoInputStream {public static void main(String[] args) throws IOException  {File f=new File("hello.txt");InputStream is=new FileInputStream(f);int available = is.available();//有大小限制  可能会超过int的最大值byte[] buf=new byte[available];//只读一次int read = is.read(buf);System.out.println(new String(buf,0,read));System.out.println(available);}//2321    //9152private static void run2() {//1.创建文件对象File f=new File("hello.txt");//2.创建输入流对象InputStream is=null;StringBuffer sb=new StringBuffer();long begin = System.currentTimeMillis();try {is=new FileInputStream(f);byte[] buf=new byte[1024];//一般写1024或者1024的整数倍int length=0;while((length=is.read(buf))!=-1){sb.append(new String(buf,0,length));}} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}finally {//释放资源try {if(is!=null){is.close();}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}//System.out.println(sb);long end = System.currentTimeMillis();System.out.println(end-begin);}}//2843   11782private static void run1() {//1.创建文件对象File f=new File("hello.txt");//2.创建输入流对象InputStream is=null;StringBuffer sb=new StringBuffer();long begin = System.currentTimeMillis();try {is=new FileInputStream(f);byte[] buf=new byte[10];//一般写1024或者1024的整数倍int length=0;while((length=is.read(buf))!=-1){sb.append(new String(buf,0,length));}} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}finally {//释放资源try {if(is!=null){is.close();}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println(sb);long end = System.currentTimeMillis();System.out.println(end-begin);}}private static void test5() {//1.创建文件对象File f=new File("hello.txt");//2.创建输入流对象InputStream is=null;StringBuffer sb=new StringBuffer();try {is=new FileInputStream(f);byte[] buf=new byte[1024];//一般写1024或者1024的整数倍int length=0;while((length=is.read(buf))!=-1){sb.append(new String(buf,0,length));}} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}finally {//释放资源try {if(is!=null){is.close();}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println(sb);}}/** * 读取文本   * @throws FileNotFoundException * @throws IOException */private static void test4() throws FileNotFoundException, IOException {//1.创建文件对象File f=new File("hello.txt");//2.创建输入流对象InputStream is=new FileInputStream(f);//3.读byte[] buf=new byte[1024];int length=0;int i=0;while((length=is.read(buf))!=-1){System.out.println(++i);System.out.println(new String(buf,0,length));}is.close();}/** * 缓冲数组:为了提高效率,每次先读取到数组里, *  *  * 读取字节数组  乱码 * @throws FileNotFoundException * @throws IOException */private static void test3() throws FileNotFoundException, IOException {//1.创建文件对象File f=new File("hello.txt");//2.创建输入流对象InputStream is=new FileInputStream(f);//3.读byte[] buf=new byte[4];int length=is.read(buf);//length是字节的个数System.out.println(length);System.out.println(new String(buf));System.out.println(new String(buf,0,length));//4.关is.close();}/** * 读取字节数组 * @throws FileNotFoundException * @throws IOException */private static void test2() throws FileNotFoundException, IOException {//1.创建文件对象File f=new File("hello.txt");//2.创建输入流对象InputStream is=new FileInputStream(f);//3.读byte[] buf=new byte[30];int length=is.read(buf);//length是字节的个数System.out.println(length);System.out.println(new String(buf));System.out.println(new String(buf,0,length));//4.关is.close();}/** * 一个字节一个字节读取:别取中文 * @throws FileNotFoundException * @throws IOException */private static void test1() throws FileNotFoundException, IOException {//1.创建文件对象File f=new File("hello.txt");//2.创建字节输入流对象InputStream is=new FileInputStream(f);//3.调用read()方法读int read = is.read();//读取的字节   int read1 = is.read();//读取的字节   int read2 = is.read();//读取的字节   int read3 = is.read();//读取的字节   System.out.println(read+"=="+(char)read);System.out.println(read1+"=="+(char)read1);System.out.println(read2+"=="+(char)read2);System.out.println(read3+"=="+(char)read3); //读到文件末尾是-1//4.释放资源  close()is.close();}}


输出流OutputStream  -> FileOutputStream (操作完成后记得关闭资源!!)

package com.serendipity.io;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStream;/** * 字节输出流:用java程序  写入数据到文件 * OutputStream * FileOutputStream *  * 构造: * FileOutputStream(File file)           创建一个向指定 File 对象表示的文件中写入数据的文件输出流。                FileOutputStream(String name)           创建一个向具有指定名称的文件中写入数据的输出文件流。                            FileOutputStream(File file, boolean append)默认false表示不追加     true表示追加          创建一个向指定 File 对象表示的文件中写入数据的文件输出流。                                         *  *  void close()           关闭此输出流并释放与此流有关的所有系统资源。  void flush()           刷新此输出流并强制写出所有缓冲的输出字节。  void write(byte[] b)           将 b.length 个字节从指定的 byte 数组写入此输出流。  void write(byte[] b, int off, int len)           将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此输出流。 abstract  void write(int b)           将指定的字节写入此输出流。  *  * @author Serendipity * */public class DemoOutPutStream {public static void main(String[] args) {}/** * 写出数据  抓取 */private static void test3() {File f=new File("2.txt");OutputStream os=null;try {os=new FileOutputStream(f,true);String data="哈哈哈哈嘿嘿嘿嗷嗷嗷";os.write(data.getBytes());} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}finally {if(os!=null){try {os.flush();os.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}/** * 输出  字节数组 * @throws FileNotFoundException * @throws IOException */private static void test2() throws FileNotFoundException, IOException {//1.创建文件对象//2.创建输出流对象OutputStream os = new FileOutputStream(new File("2.txt"),true);//OutputStream os1 = new FileOutputStream("2.txt");//3.准备数据String data="\r\n你好小姐姐~~~";//在windows系统上 写入文本的时候 \r\n一起用表示换行byte[] buf = data.getBytes();os.write(buf);System.out.println("hello\nworld");//在控制台上\r  或者 \n都表示换行os.flush();os.close();}/** * 字节输出流  单个字符写出 * @throws FileNotFoundException * @throws IOException */private static void test1() throws FileNotFoundException, IOException {//1.创建文件对象File f=new File("2.txt");//2.创建输出流对象OutputStream os=new FileOutputStream(f,true);//3.写入os.write(99);//4.释放资源os.flush();//刷新os.close();//关闭    close()有flush()的功能  为了保险  两个都写  先  flush()后close()}}

练习:将一个文件中的内容复制到另外一个文件中(图片也可以复制)

package com.serendipity.day17.study;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;/** * @author Serendipity * */public class IOCopy {public static void main(String[] args) {File f1 = new File("E:\\小苍老师.jpg");File f2 = new File("src/com/serendipity/day17/study/小姐姐1.jpg");copy1(f1, f2);}/** * 第一种方法 */public static void copy1(File srcFile, File newFile) {InputStream is = null;OutputStream os = null;try {is = new FileInputStream(srcFile);os = new FileOutputStream(newFile);byte[] buf = new byte[1024];int length = 0;while ((length = is.read(buf)) != -1) {os.write(buf, 0, length);}} catch (Exception e) {e.printStackTrace();} finally {if (is != null) {try {is.close();} catch (IOException e) {e.printStackTrace();}}if (os != null) {try {os.flush();is.close();} catch (IOException e) {e.printStackTrace();}}}}/** * 第二种方法 */public static void copy(File srcFile, File newFile) {InputStream is = null;OutputStream os = null;try {is = new FileInputStream(srcFile);byte[] buf = new byte[is.available()];is.read(buf, 0, is.available());os = new FileOutputStream(newFile);os.write(buf);} catch (IOException e) {e.printStackTrace();} finally {if (is != null) {try {is.close();} catch (IOException e) {e.printStackTrace();}}if (os != null) {try {os.flush();is.close();} catch (IOException e) {e.printStackTrace();}}}}}




原创粉丝点击