Java--IO

本文介绍了Java中的IO操作,包括File类的使用,如创建、删除和获取文件信息。还讨论了字节流和字符流在文件内容读写中的应用,以及如何使用缓冲流提高大文件操作的效率。此外,文章提供了一个递归遍历文件夹的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java的IO操作

文件类

文件操作

File fileName=new File(filePath);
fileName.getName();
fileName.getPath();
fileName.getParent();
File类中常用的方法

File类其实就是两个内容:1、对文件进行操作:创建、删除、重命名、查找等等;2、对文件路径进行操作。不能具体的内容进行操作,比如进行写入,添加,删除内容等等,这是

//直接通过 
/*

File newFile = new File(newFilePath);这个不能直接创建文件,需要用try...catch一下。。。不知道是个什么原因。
*/
        File folder = new File(fatherPath);
        try {
            File newFile = new File(newFilePath);
            if (newFile.createNewFile()) {
                System.out.println("文件创建成功:" + newFile.getName());
            } else {
                System.out.println("文件已经存在");
            }
//          NOTE 常用方法
            System.out.println("文件的绝对路径:" + newFile.getAbsolutePath());
            System.out.println("文件的路径" + newFile.getPath());
            System.out.println("文件名称:" + newFile.getName());
            System.out.println("文件的长度:" + newFile.length());
        } catch (IOException e) {
            System.out.println(e);
        } finally {
            System.out.println("end!!");
        }

文件的遍历

package File;

import java.io.File;

//递归遍历文件夹下所有的文件
public class FileList {
    public static void main(String[] args) {
        String filePath = "D:\***\\JavaLearn\\Basic\\collection";
        File file = new File(filePath);
//        ArrayList<String> fileNameList=new ArrayList<>();
        ArrayList result=Recursion(file);
        System.out.println(result);

    }

    public static ArrayList Recursion(File file) {
        ArrayList<String> fileNames=new ArrayList<>();
        if (!file.isDirectory()) {
            return fileNames;
        }
        File[] files =file.listFiles();
        for(File f :files){
            if(f.isDirectory()){
                Recursion(f);
            }else {
                fileNames.add(f.getName());
                System.out.println(f.getName());
            }
        }
        return fileNames;
    }
}

文件内容的操作

文件内容的操作主要是两种:字节流域字符流,
一般来说字节流用来处理一些二进制的读写,比如图像视频等等,字符流用来处理字符串的读写,字符串也能用字节流来处理,只是字符流更方便。

字节流内容读写

字节流是最基本的IO处理操作,但是对于一些中文的字符来说,处理起来容易出现乱码,比如下面—这里我是一个中文----打印就是会出现乱码。

       public static void fileCreateOrNot(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            try {
                file.createNewFile();

            } catch (IOException e) {
                System.out.println("文件不存在,且创建成功");
            }
        }
    }

    public static void fileWriteOutputStream(String filePath) {
        /**首先要执行以下看看文件是否存在,如果不存在就创建一个*/
        fileCreateOrNot(filePath);
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(filePath);
            String content = "1 this is a java io test module!" + "I want to write something into a text file." + "so I am here,这里我是一个中文";
//            fileOutputStream.skip(2);
            fileOutputStream.write(content.getBytes());
        } catch (IOException e) {
            System.out.println("file write failed");
        } finally {
            System.out.println("end!");
        }
    }

    public static void fileReadeInputStream(String filePath) {
        try {
            FileInputStream inputStream = new FileInputStream(filePath);
            int content = inputStream.read();
            while (content != -1) {
                System.out.print((char) content);
                content = inputStream.read();
//                TimeUnit.SECONDS.sleep(1);
                TimeUnit.MILLISECONDS.sleep(100);
            }

        } catch (FileNotFoundException e) {
            System.out.println("file not found");
        } catch (IOException e) {
            System.out.println("file read failed!");
        } catch (InterruptedException e) {
            System.out.println("no meaning");
        }
    }
   public static void main(String[] args) {
        String filePath="D:\\***\\src\\main\\java\\org\\example\\data\\delta.txt";
        fileWriteOutputStream(filePath);
        fileReadeInputStream(filePath);
    }

字符流内容读写

    public static boolean fileExists(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                System.out.println("文件创建失败");
                return false;
            }
        }
        return true;
    }

    public static void fileReader(String filePath) {
//        fileExists(filePath);
        try {
            FileReader fileReader = new FileReader(filePath);
            int content;
            while ((content = fileReader.read()) != -1) {
                System.out.println(((char) content));
            }

        } catch (FileNotFoundException e) {
            System.out.println("没有找到文件");
        } catch (IOException e) {
            System.out.println("文件读取失败");
        }
    }

    public static void fileWriter(String filePath) {

        if (fileExists(filePath)) {
            String writerStr = "这里是一个测试,用来测试中文字符的输入是否正常;" + "this is a test ,about chinese char is normal";
            try {
                Writer fileWriter = new FileWriter(filePath);
                fileWriter.write(writerStr);
            } catch (IOException e) {
                System.out.println("文件写入IO异常");
            }
            System.out.println("----------");
            try {
                TimeUnit.MILLISECONDS.sleep(3000);
            } catch (InterruptedException e) {
                System.out.println();
            }
            fileReader(filePath);

        } else {
            System.out.println("重新修改吧,傻子");
        }

    }

    public static void testFunc() {
        String filePath = "D:\\****\\src\\main\\java\\org\\example\\data\\beta.txt";

        String content = "这里是一个小的测试,用来测试中文字符的输入" +
                "this is a test,for chinese char write";
        try (FileWriter fileWriter = new FileWriter(filePath)) {
            fileWriter.write(content);
        } catch (IOException e) {
            System.out.println("有异常");
        }

    }

    public static void main(String[] args) {
        String filePath = "D:\\****\\src\\main\\java\\org\\example\\data\\delta.txt";
//        fileWriter(filePath);
        testFunc();
    }

字符缓冲流内容读写

在面对一些大文件的读写操作,常见的文件操作都变得非常缓慢,IO是非常消耗资源的一种操作,所以就出现了字符缓冲流,相对于原始的操作,极大地加快了速度。

    public static boolean fileCreate(String filePath) {
        File file = new File(filePath);
        try {
            if (file.createNewFile()) {
                System.out.println("文件建立成功");
            } else {
                System.out.println("文件创立失败");
                return false;
            }
        } catch (IOException e) {
            System.out.println(e.getStackTrace());
        }
        return true;
    }

    public static void fileReadBuffer(String filePath) {
        if (fileCreate(filePath)) {
            try (BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath))) {
                int content;
                while ((content = bufferedReader.read()) != -1) {
                    System.out.println("happened");
                    System.out.println(content);
                    TimeUnit.MILLISECONDS.sleep(300);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                System.out.println(e);
            }
        } else {
            System.out.println("文件不存在");
        }

    }

    public static void fileWriteBuffer(String filePath) {
        String strS="this is a 用来测试IO buffer的案例,这里测的不是用来测试速度,而是用来测试" +
                "是否能够运行";
        try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filePath))) {
            bufferedWriter.write(strS);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {
        String filePath="D:\\***\\src\\main\\java\\org\\example\\data\\epsilon.txt";
//        fileReadBuffer(filePath);
        fileWriteBuffer(filePath);
    }

一个简单的文件文件创建写入读取(如果存在就删除重新创建写入跟读取)

public class Gramma {
    public static void main(String[] args) {
        String filePath = "D:\\***\\Basic\\collection\\files\\file.txt";
        String[] contents=fileContent();
/*1、文件的check,如果有的话就删除
  2、创建一个文件,并写入一个array;
  3、把文件读到terminal上。
**/
        fileCheckout(filePath);
        newFile(filePath, contents);
        fileReader(filePath);
    }

    public static void fileCheckout(String filePath){
        File file =new File(filePath);
        if(file.exists()){
            file.delete();
        }
    }
    public static String[] fileContent(){
        String [] contents={"alpha","beta","gamma","delta"};
        return contents;
    }

    public static void fileReader(String filePath){
        try{
            FileReader file=new FileReader(filePath);
           int content;
           while ((content=file.read())!=-1){
               System.out.println(String.valueOf(content));
           }
        }catch (IOException e){
            System.out.println(e);
        }
        finally {
            System.out.println("文件读取结束");
        }
    }
    public static void newFile(String filePath,String[]contents) {
        /*NOTE 创建一个.txt文件,然后写入字符串。
        * */
        try {
            File file = new File(filePath);
            if (file.createNewFile()) {
                System.out.println("文件创建成功!" + file.getName());
                FileWriter fileWriter=new FileWriter(filePath);
                for(String con:contents){
                    fileWriter.write(con+"\n");
                }
                fileWriter.close();
            } else {
                System.out.println("文件已经存在");

            }

        } catch (IOException e) {
            System.out.println("文件查找不到!");
        } finally {
            System.out.println("end");
        }

    }


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值