Java——I/O相关练习代码


File文件的相关练习

文件操作的三种方式:

    public static void main(String[] args) {
        //用File表示D:/IoFile/File/File.txt
        File f1 = new File("D:/IoFile/File/File.txt");
        File f2 = new File("D:/IoFile/File","File.txt");
        //文件夹
        File parent = new File("D:/IoFile/File");
        //文件
        File f3 = new File(parent,"File.txt");
    }

文件的相关方法练习:

public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("输入一个文件路径,显示文件的相关属性:");
        String str1 = sc.next();
        File f1 = new File(str1);
        //文件是否存在
        System.out.println("文件存在?:"+f1.exists());
        //读写属性
        System.out.println("可读?;"+f1.canRead());
        System.out.println("可写?:"+f1.canWrite());
        //是否是目录
        System.out.println("是否是目录:"+f1.isDirectory());
        //文件的绝对路径
        System.out.println("文件的绝对路径为:"+f1.getAbsolutePath());
        //文件的上级文件
        System.out.println("文件的上级文件为:"+f1.getParent());
    }

文件创建、删除操作:

public static void main(String[] args) {
        //创建文件
        File file = new File("D:/IoFile/File/dir1/dir2");
        //创建普通文件
//      try {
//          file.createNewFile();
//          System.out.println("文件创建成功!");
//      } catch (IOException e) {
//          // TODO Auto-generated catch block
//          e.printStackTrace();
//      }   
        //创建文件夹
//      file.mkdir();
//      System.out.println("文件夹创建成功!");

        //mkdirs 递归创建文件夹
        File file1 = new File("D:/IoFile/File/File/File/file");
        System.out.println(file1.mkdirs());

        //在D:/iodemo/abc/def下创建一个文件a.txt
        File parent = new File("D:/iodemo/abc/def");
        File a = new File(parent,"a.txt");
        //判断文件夹是否存在
        if(!parent.exists()){
            //不存在先创建文件夹
            parent.mkdirs();
        }
        try {
            //文件创建成功
            a.createNewFile();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

文件练习:

输出一个文件夹中的所有文件、普通文件、以及文件夹的大小。

public static void main(String[] args) {
        String str = "D:/IoFile/File";
        File f = new File(str);
        int count=0;
        int totalsize=0;
        if(f.exists()){
            File[] files = f.listFiles();
            System.out.println("所有文件个数是:"+files.length);
            //循环遍历所有文件
            for(int i = 0;i<files.length;i++){
                if(files[i].isFile()){
                    //普通文件个数
                    count++;
                    //文件大小
                    //文件夹没有大小,若文件夹里有文件,则文件夹大小为文件大小之和
                    totalsize+=files[i].length();
                }
            }
            System.out.println("普通文件个数是:"+count);
            System.out.println("所有文件大小是:"+(float)totalsize/1024+"kb");
        }else{
            System.out.println("该文件夹不存在!");
        }
    }

FileReader读取文件

public static void main(String[] args) {
        //读取文件
        File f = new File("D:/IoFile/File/fileReader.txt");
        FileReader fr=null;
        try {
            fr = new FileReader(f);
            char[] c = new char[1024];
            int len=0;
            StringBuffer sb= new StringBuffer();
            while((len=fr.read(c,0,10))!=-1){
                //把读取到的内容存放到sb中 
                sb.append(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 {
                if(fr!=null) {
                    fr.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

读取文件逐行读取

        //读取文件
        File f = new File("D:/IoFile/File/fileReader.txt");
        FileReader fr=null;
        BufferedReader br = null;

            fr = new FileReader(f);
            br = new BufferedReader(fr);
            String str =null;
            //逐行读取
            while((str=br.readLine())!=null){
                System.out.println(str);
            }

InputStreamReader(字符输出流)

public static void main(String[] args) {
        //字节流转字符流
        FileInputStream fis=null;
        InputStreamReader isr = null;
        BufferedReader br =null;
        try {
            fis = new FileInputStream("D:/IoFile/File/isr.txt");
            isr = new InputStreamReader(fis);
            br = new BufferedReader(isr);
            StringBuffer sb = new StringBuffer();
            String str=null;
            while((str=br.readLine())!=null){
                sb.append(str+"
");
            }
            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{
                if(br!=null){
                    br.close();
                }
            }catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

换行输出


        FileWriter fw=null;

            fw = new FileWriter("D:/IoFile/fw.txt");
            // 
 换行
            fw.write("求知若饥
");
            fw.write("噼里啪啦");
            System.out.println("写入成功!");

BufferedWriter

换行输出

        BufferedWriter bw = null;
        try {
            bw = new BufferedWriter(new FileWriter("D:/IoFile/File/bw.txt"));
            bw.write("第一段测试");
            //换行
            bw.newLine();
            bw.write("测试第二段");
            System.out.println("写入成功!");
        }

FileOutputStream

        try {
            //把程序和目标源建立连接
            FileOutputStream fos = new FileOutputStream("D:/IoFile/out.txt");
            //把字符串转成字节数组
            String str = "求知若愚,虚心若饥";
            fos.write(str.getBytes());
            //flush 把数据完全冲刷到目标源中
            fos.flush();
            fos.close();
            System.out.println("文件写入成功!");

        } 

BufferedOutputStream

try {
            //把程序和目标源建立连接
            //Buffer更加安全
            //直接传文件名,默认覆盖原有内容
            //文件名+true;在原有内容后追加新内容
//          BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("D:/IoFile/buffer.txt"));
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("D:/IoFile/buffer.txt",true));
            //把字符串转成字节数组
            String str = "求知若愚,虚心若饥";
            bos.write(str.getBytes());
            //flush 把数据完全冲刷到目标源中
            bos.flush();
            bos.close();
            System.out.println("文件写入成功!");

        }

DataOutputStream

        try {
            //写入
            DataOutputStream dos = new DataOutputStream(new FileOutputStream("D:/IoFile/data.txt"));
            dos.writeBoolean(true);
            dos.writeInt(110);
            dos.writeUTF("求知若饥");
            dos.flush();
            dos.close();
            System.out.println("写入成功!");

        }

PrintStream

//构造参数传System,out,就是在控制台打印信息
//      PrintStream ps = new PrintStream(System.out);
//      ps.print("132546u");
        try {
            PrintStream ps1=
                    new PrintStream
                    (new FileOutputStream("D:/IoFile/print.txt"));
            ps1.println("虚心若愚");
            ps1.println("求知若饥");
            ps1.println("求知若饥");
            ps1.println("虚心若愚");
            ps1.flush();
            ps1.close();
            System.out.println("写入成功!");
        }
原文地址:https://www.cnblogs.com/aixing/p/13327727.html