当前位置: 移动技术网 > IT编程>开发语言>Java > IO流

IO流

2018年08月19日  | 移动技术网IT编程  | 我要评论

File类

添加方法:

1.创建普通文本文档:boolean flag= file1.createNewFile();
2.创建文件夹:boolean flag2=file2.mkdir();
3.同时创建多个文件夹:boolean flag3=file3.mkdirs();

public class fileDemo1 {
    public static void main(String[] args) {
        
        try {
            //不管D盘是否有这个文档,如果有这个文件,创建失败,否则,创建成功
            File file1= new File("D:\\9504.txt");
            //创建一个新的普通文件
            boolean flag= file1.createNewFile();
            System.out.println(flag?"创建成功":"创建失败");
            //创建一个文件夹
            File file2 = new File("D:\\9504_java");
            boolean flag2=file2.mkdir();
            System.out.println(flag2?"文件夹创建成功":"文件夹创建失败");
            //同时创建多个文件夹
            File file3 = new File("D:\\java\\web\\html");
            boolean flag3=file3.mkdirs();
            System.out.println(flag3?"多个文件夹创建成功":"多个文件夹创建失败");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

删除文件:

public static void main(String[] args) {
        File file1= new File("D:\\9504.txt");
        boolean flag=file1.delete();
        System.out.println(flag?"删除成功":"删除失败");
    }
}

查询文件:

1.判断某个文件夹是否存在

 public static void main(String[] args) {
        File file1 = new File("E:\\javaSE");
        //判断某个路径的文件是否存在
        boolean flag1=file1.exists();
        if (flag1){
            System.out.println("您的文件夹已经存在,不需要在创建新的文件夹");
        }else {
           boolean flag= file1.mkdir();
            System.out.println("创建文件夹成功");
        }
    }

对文件的操作:

 //获取文件大小
        File file2 = new File("E:\\20202020");
        try {
            boolean flag2=file2.createNewFile();
            System.out.println(flag2?"创建文本成功":"创建失败");
            Long size=file2.length();
            System.out.println("size="+size);
            //获取文件名
            String fileName=file2.getName();
            System.out.println("fileName="+fileName);
            //获取文件路径
            String path=file2.getPath();
            System.out.println("path="+path);
        } catch (IOException e) {
            e.printStackTrace();
        }

运行结果:
file

常见面试题目:
获取文件的大小:
String 字符串: length(),返回字符串中字符的个数
数组: 数组名.length,是属性,获取数组中元素的个数 int[]
集合: 集合对象名.size(),返回集合中元素的个数
String 一般第一个字母是大写的,后边用方法,一般情况下试用

递归遍历文件夹下所有文件***

递归:方法自己调用自己
isDirectory():判断文件是否是文件夹
listFiles():查询某个文件夹下面的所有文件

//高级for循环
for(数据类型  变量名:数组/集合){
}

举例:


    public static void showFile(String pathName){
        File f1=new File(pathName);
        //判断文件夹是否存在
        boolean flag1=f1.isDirectory();
        //选择某个文件下面的所有文件
        if(flag1){//如果是文件夹
            File[] files=f1.listFiles();
            for (File tempFile:files){//高级for循环
                boolean flag2=tempFile.isDirectory();
                if (flag2){//是文件夹
                    showFile(tempFile.getPath());
                }else{
                    String path =f1.getPath();
                    System.out.println("获取普通文件路径为:"+path);
                }
            }

        }else {//如果不是一个文件夹
            String path =f1.getPath();
            System.out.println("获取普通文件路径为:"+path);
        }
    }

    public static void main(String[] args) {
        fileDemo1.showFile("D:\\");
    }
}

showFile(tempFile.getPath());这个方法就是把刚才的方法在重新调用一遍

这时会报错:

//此时会有报错出现
//Exception in thread "main" java.lang.NullPointerException
//        at com.shmily.lesson2.fileDemo1.showFile(fileDemo1.java:15)
//        at com.shmily.lesson2.fileDemo1.showFile(fileDemo1.java:18)
//        at com.shmily.lesson2.fileDemo1.showFile(fileDemo1.java:18)
//        at com.shmily.lesson2.fileDemo1.main(fileDemo1.java:32)

递归BUG解决:


    public static void showFile(String pathName){
        File f1=new File(pathName);
        //判断文件夹是否存在
        boolean flag1=f1.isDirectory();
        //选择某个文件下面的所有文件
        if(flag1){//如果是文件夹
            File[] files=f1.listFiles();
            for (int i=0;files!=null && i<files.length;i++){//普通for循环
                boolean flag2=files[i].isDirectory();
                if (flag2){//是文件夹
                    showFile(files[i].getPath());
                }else{
                    String path =f1.getPath();
                    System.out.println("获取普通文件路径为:"+path);
                }
            }

运行结果为:
file

IO流*输入输出流

字节流:可以读取一切文件

字节输入流

我的理解就是键盘上的数字或者文件中的东西通过程序去实现就是称为字节输入流。
输入流

ublic class InputTest {
    public static void main(String[] args) {
        try {
            //1.在文件和程序之间铺设管道方法一
            FileInputStream file=new FileInputStream("D:\\0208.txt");
            //方法二
            File f1 = new File("D:\\0208.txt");
            if (f1.exists() && f1.length()>0){
                FileInputStream fi=new FileInputStream(f1);
            }
            //2.打开水龙头,每次只读取一个字符
            int ch=file.read();
            System.out.println("ch="+(char)ch);
            //获取全部字符
            int ch1=0;
            while ((ch1=file.read())!=-1){
                System.out.print((char) ch1);
            }
            //3.关闭水龙头(关闭流)
            file.close();
        } catch (Exception e) {
            System.out.println("文件不存在");
        }
    }
}

注意:FileInputStream的缺点是一个字节一个字节的去读,而当文件中有中文时,在国际上的utf-8中,一个中文字占据3个字节,在我们本国的中文中GB中一个汉字占据两个字节,read是一个字节一个字节的去读的,并不会拼接,所以读取中文的时候出现乱码是正常的。

BufferedInputStream字节缓冲输入流

 public static void main(String[] args) {
        try {
            long startTime=System.currentTimeMillis();

            //1.铺设管道
            FileInputStream fil = new FileInputStream("D:\\28.txt");
            BufferedInputStream buf = new BufferedInputStream(fil);
            //2.开水龙头创建一辆小车,每次可以运输1024快砖
            byte[]car=new byte[1024];
            int len=0;
            while ((len=buf.read(car))!=-1){
                System.out.println(len);
            }
            buf.close();
            long endTime=System.currentTimeMillis();
            System.out.println("一共消耗了"+(endTime-startTime)+"ms");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

字节输出流

输出流
字节输出流:

  1. 有水厂
  2. 铺设管道(FileOutputStream、BufferedOutputStream)
  3. 输出数据,关流
public class OutputTest {
    public static void main(String[] args) {
        try {
            //1.创建水厂
            String data="hello word,hello java!";
            //铺设程序通往盘符的管道
            FileOutputStream fos=new FileOutputStream("D:\\28.txt",true);
            //3.开水龙头,放水,写
            byte[] tempByte=data.getBytes();
            //如果文件不存在,则帮我们直接创建该文件
            fos.write(tempByte);
            //关闭管道
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

注意:如果 FileOutputStream fos=new FileOutputStream(“D:\28.txt”,true);的 第二个参数不写,在每次执行一次程序,都会把原来的字符覆盖,如果后面加了true,则紧挨着最后一个字符来往下写

继承关系
BufferedOutputStream字节缓冲输出流

public static void main(String[] args) {
        try {
            long startTime=System.currentTimeMillis();
            FileInputStream fil = new FileInputStream("D:\\28.txt");
            BufferedInputStream buf = new BufferedInputStream(fil);
            OutputStream fos = new FileOutputStream("E:\\823.txt");
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            byte[] car=new byte[1024];
            int len=0;//0表示下标,len表示car里面的具体的个数
            while ((len=buf.read(car))!=-1){
                bos.write(car,0,len);
            }
            buf.close();
            bos.close();
            long endTime=System.currentTimeMillis();
            System.out.println("共消耗了"+(endTime-startTime)+"ms");
        } catch (Exception e) {
            e.printStackTrace();
        }

此处应该注意的是write方法中的参数,off代表car这个数组的下标,len代表car这个数组中具体的东西的个数
write

输入输出的综合应用,即复制

把D盘的文件复制到E盘的操作,同时加入了复制的时间计算
复制

  public static void main(String[] args) {
        try {
            long startTime=System.currentTimeMillis();

            FileInputStream fis = new FileInputStream("D:\\0208.txt");
            FileOutputStream fos = new FileOutputStream("E:\\0208.txt");

            int ch=0;
            while ((ch=fis.read())!=-1){
                fos.write(ch);
            }
            fis.close();
            fos.close();
            //时间是按ms计算的
            long endTime=System.currentTimeMillis();
            System.out.println("一共消耗了"+(endTime-startTime)+"ms");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

字符流:读取纯文本文件比较方便

  1. 字符输入流
    Reader
 public static void main(String[] args) {
        try {
            //水厂
            FileReader fiR = new FileReader("D:\\28.txt");
            //2.开水龙头
            char[] car=new char[1024];
            int len=0;
            while ((len=fiR.read(car))!=-1){
                System.out.println(len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

如果文本文件中是中文,例如是中国两个字,想要转换,这是强行准换好像不成功,就换了一种方法来转换。利用String去转换,此时是成功的。

//强行转换

        try {
            FileReader fil = new FileReader("D:\\0208.txt");
            char[] car=new char[1024];
            int len=0;
            while ((len=fil.read(car))!=-1){
                System.out.println(car[0]+car[1]+"");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }//输出的结果是42282
  try {
            FileReader fil = new FileReader("D:\\0208.txt");
            char[] car=new char[1024];
            int len=0;
            while ((len=fil.read(car))!=-1){
                String str=new String(car,0,len);
                System.out.println(str);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }//输出的结果是中国
  1. 字符输出流
    Writer
 public static void main(String[] args) {
        try {
            //水厂
            String str="java学习很简单,我爱学习Java!";
            //铺设管道
            FileWriter writer = new FileWriter("D:\\0823.txt");
            //打开水龙头
            writer.write(str);
            //关闭水龙头
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

本文地址:https://blog.csdn.net/weixin_46178009/article/details/105955425

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网