search
HomeJavajavaTutorialJava basics: I/O streams and File class file operation methods

    ♒I/O流原理及流的分类

    I/O原理

    • I/O是Input和Output的缩写,I/O技术是非常实用的技术,用于处理数据传输(如:读/写文件,网络通信)

    • Java程序中,对于数据的输入/输出操作是以流(stream)的方式进行的

    • java.io包下提供了各种流(stream)类和接口,用以获取不同种类的数据,并通过方法输入和输出数据。

    • 文件流:文件在程序中是以流的形式操作的

    Java basics: I/O streams and File class file operation methods

    输入流:数据从数据源(文件)到程序(内存)的路径

    输出流:数据从程序(内存)到数据源(文件)的路径

    I/O流的分类

    • 按操作数据单位分为:字节流(二进制文件)、字符流(文本文件)

    • 按数据的流向分为:输入流、输出流

    • 按流的角色分为:节点流、处理流

    抽象基类 字节流 字符流
    输入流 InputStream Reader
    输出流 OutputStream Writer

    ♨️I/O的体系结构

    Java basics: I/O streams and File class file operation methods

    文件(File)

    概念

    什么是文件?

    文件,对于我们并陌生,文件就是保存数据的地方,比如word文档、txt文本、excel文件、图片、视频…等都是文件,操作系统中以文件为单位管理磁盘中的数据。从数据存储角度来说,所有文件本质上都是一样的,都是由一个个字节组成的归根到底都是0-1比特串。

    文件夹(目录)

    多个文件如果不分类放在一起,用户使用起来就非常不方便,因此,又引入了树形目录(也叫文件夹)的机制,可以把文件放在不同的文件夹中,文件夹中还可以嵌套文件夹,这就便于用户对文件进行管理和使用。

    ✍️常用操作(File类)

    创建文件对象相关构造器和方法

    new File(String pathname);//根据路径构建一个File对象
    new File(File parent,String child);//根据父目录文件+子路径构建
    new File(String parent,String child);//根据父目录路径+子路径构建
    createNewFile();//创建新文件

    在E盘下,用以上方式创建文件test01.txt\test02.txt\test03.txt

    import java.io.File;
    import java.io.IOException;
    
    public class FileCreate {
        public static void main(String[] args) throws IOException {
            //方式1
            String pathname = "e:\\test01.txt";
            File file1 = new File(pathname);
            file1.createNewFile();
            //方式2
            File parentfile = new File("e:\\");
            String child2 = "test02.txt";
            File file2 = new File(parentfile, child2);
            file2.createNewFile();
            //方式3
            String parent = "e:\\";
            String child3 = "test03.txt";
            File file3 = new File(parent, child3);
            file3.createNewFile();
        }
    }

    Java basics: I/O streams and File class file operation methods

    获取文件的相关信息

    get.getName();//获取文件名字

    canRead();//文件是否可读

    canWrite();//文件是否可写

    getAbsoultePath();//获取文件的绝对路径

    getPath();//相对路径

    getParent();//获取文件父级目录

    lenth();//文件大小(字节)

    exists();//判断文件是否存在

    isFile();//判断是不是一个文件

    isDirectory();//判断是不是一个目录

    import java.io.File;
    public class FileInfomation {
        public static void main(String[] args) {
            //创建文件对象
            File file = new File("e:\\test01.txt");
            System.out.println("文件名字:" + file.getName());
            System.out.println("文件是否可读:" + file.canRead());
            System.out.println("文件是否可写:" + file.canWrite());
            System.out.println("文件绝对路径:" + file.getAbsolutePath());
            System.out.println("文件大小(字节):" + file.length());
            System.out.println("文件是否存在:" + file.exists());
            System.out.println("是不是一个文件:" + file.isFile());
            System.out.println("是不是一个目录:" + file.isDirectory());
        }
    }

    Java basics: I/O streams and File class file operation methods

    文件比较

    File f1=new File("D:\\test1.txt");
    File f2=new File("D:\\test2.txt");
    f1==f2;//比较的是两个对象的地址
    f1.equals(f2);//比较两个对象对应的文件的路径

    目录操作和文件删除

    mkdir();//创建单层目录

    mkdirs();//创建多层目录

    delete();//删除目录(这层目录必须为空,没有内容)

    查看文件目录

    list();//返回一个字符串数组,命名由此抽象路径名表示的目录中的文件和目录。

    listFiles();//返回一个抽象路径名数组,表示由该抽象路径名表示的目录中的文件。

    案列:遍历一个目录下的所有文件打印输出

    public class PrintFile {
        public static void main(String[] args) {
            //创建文件对象
            File file = new File("e:\\Test");
            String[] list = file.list();//文件夹下目录/文件对应的名字的数组
            for (String s : list) {
                System.out.println(s);
            }
            File[] files = file.listFiles();
            for (File f : files) {
                System.out.println(f.getName() + "," + f.getAbsolutePath());
            }
        }
    }

    Java basics: I/O streams and File class file operation methods

    遍历目录

    1.给定一个文件对象file
    2.listFiles()获取该文件下的所有文件对象数组
    3.遍历File对象数组,如果是目录,递归调用该方法获取该目录下的所有文件对象;如果是文件,打印输出路径+姓名

    import java.io.File;
    
    public class PrintFile {
        public static void main(String[] args) {
            File file = new File("E:\\Code");
            getAllFile(file);
        }
    
        public static void getAllFile(File file) {
            //获取给定目录下的所有File对象数组
            File[] files = file.listFiles();
            //开始遍历
            if (files != null) {
                for (File f : files) {
                    if (f.isDirectory()) {//判断是否为目录,如果是,调用递归
                        getAllFile(f);
                    } else {//不是,就打印路径+文件名
                        System.out.println(f.getAbsoluteFile() + "下的:" + f.getName());
                    }
                }
            }
        }
    }

    The above is the detailed content of Java basics: I/O streams and File class file operation methods. For more information, please follow other related articles on the PHP Chinese website!

    Statement
    This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
    Is Java Platform Independent if then how?Is Java Platform Independent if then how?May 09, 2025 am 12:11 AM

    Java is platform-independent because of its "write once, run everywhere" design philosophy, which relies on Java virtual machines (JVMs) and bytecode. 1) Java code is compiled into bytecode, interpreted by the JVM or compiled on the fly locally. 2) Pay attention to library dependencies, performance differences and environment configuration. 3) Using standard libraries, cross-platform testing and version management is the best practice to ensure platform independence.

    The Truth About Java's Platform Independence: Is It Really That Simple?The Truth About Java's Platform Independence: Is It Really That Simple?May 09, 2025 am 12:10 AM

    Java'splatformindependenceisnotsimple;itinvolvescomplexities.1)JVMcompatibilitymustbeensuredacrossplatforms.2)Nativelibrariesandsystemcallsneedcarefulhandling.3)Dependenciesandlibrariesrequirecross-platformcompatibility.4)Performanceoptimizationacros

    Java Platform Independence: Advantages for web applicationsJava Platform Independence: Advantages for web applicationsMay 09, 2025 am 12:08 AM

    Java'splatformindependencebenefitswebapplicationsbyallowingcodetorunonanysystemwithaJVM,simplifyingdeploymentandscaling.Itenables:1)easydeploymentacrossdifferentservers,2)seamlessscalingacrosscloudplatforms,and3)consistentdevelopmenttodeploymentproce

    JVM Explained: A Comprehensive Guide to the Java Virtual MachineJVM Explained: A Comprehensive Guide to the Java Virtual MachineMay 09, 2025 am 12:04 AM

    TheJVMistheruntimeenvironmentforexecutingJavabytecode,crucialforJava's"writeonce,runanywhere"capability.Itmanagesmemory,executesthreads,andensuressecurity,makingitessentialforJavadeveloperstounderstandforefficientandrobustapplicationdevelop

    Key Features of Java: Why It Remains a Top Programming LanguageKey Features of Java: Why It Remains a Top Programming LanguageMay 09, 2025 am 12:04 AM

    Javaremainsatopchoicefordevelopersduetoitsplatformindependence,object-orienteddesign,strongtyping,automaticmemorymanagement,andcomprehensivestandardlibrary.ThesefeaturesmakeJavaversatileandpowerful,suitableforawiderangeofapplications,despitesomechall

    Java Platform Independence: What does it mean for developers?Java Platform Independence: What does it mean for developers?May 08, 2025 am 12:27 AM

    Java'splatformindependencemeansdeveloperscanwritecodeonceandrunitonanydevicewithoutrecompiling.ThisisachievedthroughtheJavaVirtualMachine(JVM),whichtranslatesbytecodeintomachine-specificinstructions,allowinguniversalcompatibilityacrossplatforms.Howev

    How to set up JVM for first usage?How to set up JVM for first usage?May 08, 2025 am 12:21 AM

    To set up the JVM, you need to follow the following steps: 1) Download and install the JDK, 2) Set environment variables, 3) Verify the installation, 4) Set the IDE, 5) Test the runner program. Setting up a JVM is not just about making it work, it also involves optimizing memory allocation, garbage collection, performance tuning, and error handling to ensure optimal operation.

    How can I check Java platform independence for my product?How can I check Java platform independence for my product?May 08, 2025 am 12:12 AM

    ToensureJavaplatformindependence,followthesesteps:1)CompileandrunyourapplicationonmultipleplatformsusingdifferentOSandJVMversions.2)UtilizeCI/CDpipelineslikeJenkinsorGitHubActionsforautomatedcross-platformtesting.3)Usecross-platformtestingframeworkss

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    Dreamweaver Mac version

    Dreamweaver Mac version

    Visual web development tools

    SAP NetWeaver Server Adapter for Eclipse

    SAP NetWeaver Server Adapter for Eclipse

    Integrate Eclipse with SAP NetWeaver application server.

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    MantisBT

    MantisBT

    Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

    DVWA

    DVWA

    Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software