广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Java文件基本操作总结
  • 858
分享到

Java文件基本操作总结

2024-04-02 19:04:59 858人浏览 安东尼

Python 官方文档:入门教程 => 点击学习

摘要

File文件类 java.io.File是文件和目录的重要类(jdk6及以前是唯一) 目录也使用File类进行表示 File类与操作系统无关,但会受到操作系

File文件类

  • java.io.File是文件和目录的重要类(jdk6及以前是唯一)
  • 目录也使用File类进行表示
  • File类与操作系统无关,但会受到操作系统的权限限制
  • 常用方法createNewFile , delete , exists , getAbsolutePath , getName , getParent , getPathisDirectory , isFile , length , listFiles , mkdir , mkdirs
  • File不涉及到具体的文件内容、只会涉及属性

public static void main(String[] args) {
    // 创建目录
    File directory = new File("D:/temp");
    boolean directoryDoesNotExists = ! directory.exists();
    if (directoryDoesNotExists) {
        // mkdir是创建单级目录
        // mkdirs是连续创建多级目录
        directory.mkdirs();

    }
    // 创建文件
    File file = new File("D:/temp/test.txt");
    boolean fileDoesNotExsits = ! file.exists();
    if (fileDoesNotExsits) {
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 遍历directory下的所有文件消息
    File[] files = directory.listFiles();
    for (File file1 : files) {
        System.out.println(file1.getPath());
    }

}

运行结果:

D:\temp\test.txt

Java NIO

  • Java 7提出的NIO包,提出新的文件系统类
  • Path , Files , DirectoryStream , FileVisitor , FileSystem
  • 是对java.io.File的有益补充
  • 文件复制和移动
  • 文件相对路径
  • 递归遍历目录
  • 递归删除目录

Path类


public static void main(String[] args) {
    // Path和java.io.File基本类似
    Path path = FileSystems.getDefault().getPath("D:/temp", "abc.txt");
    // D:/ 返回1 D:/temp 返回2
    System.out.println(path.getNameCount());

    // 用File的toPath()方法获取Path对象
    File file = new File("D:/temp/abc.txt");
    Path path1 = file.toPath();
    System.out.println(path.compareTo(path1)); // 结果为0 说明两个path相等
    // 获取Path方法三
    Path path3 = Paths.get("D:/temp", "abc.txt");
    // 判断文件是否可读
    System.out.println("文件是否可以读取: " + Files.isReadable(path));
}

Files类


public static void main(String[] args) {
    // 移动文件
    moveFile();
    // 访问文件属性
    fileAttributes();
    // 创建目录
    createDirectory();
}

private static void createDirectory() {
    Path path = Paths.get("D:/temp/test");
    try {
        // 创建文件夹
        if (Files.notExists(path)) {
            Files.createDirectory(path);
        } else {
            System.out.println("文件夹创建失败");
        }
        Path path2 = path.resolve("a.java");
        Path path3 = path.resolve("b.java");
        Path path4 = path.resolve("c.txt");
        Path path5 = path.resolve("d.jpg");
        Files.createFile(path2);
        Files.createFile(path3);
        Files.createFile(path4);
        Files.createFile(path5);

        // 不带条件的遍历输出
        DirectoryStream<Path> listDirectory = Files.newDirectoryStream(path);
        for (Path path1 : listDirectory) {
            System.out.println(path1.getFileName());
        }
        // 创建一个带有过滤器,过滤文件名以java txt结尾的文件
        DirectoryStream<Path> pathsFilter = Files.newDirectoryStream(path, "*.{java,txt}");
        for (Path item : pathsFilter) {
            System.out.println(item.getFileName());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

@SuppressWarnings("all")
private static void fileAttributes() {
    Path path = Paths.get("D:/temp");
    // 判断是否是目录
    System.out.println(Files.isDirectory(path, LinkOption.NOFOLLOW_LINKS));
    try {
        // 获取文件的基础属性
        BasicFileAttributes attributes = Files.readAttributes(path, BasicFileAttributes.class);
        // 判断是否是目录
        System.out.println(attributes.isDirectory());
        // 获取文件最后修改时间
        System.out.println(new Date(attributes.lastModifiedTime().toMillis()).toLocaleString());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private static void moveFile() {
    Path from = Paths.get("D:/temp", "text.txt");
    // 将文件移动到D:/temp/test/text.txt, 如果目标文件以存在则替换
    Path to = from.getParent().resolve("test/text.txt");
    try {
        // 文件大小bytes
        System.out.println(Files.size(from));
        // 调用文件移动方法,如果目标文件已存在则替换
        Files.move(from, to, StandardCopyOption.REPLACE_EXISTING);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

递归遍历查找指定文件


public class Demo2 {
    public static void main(String[] args) {
        // 查找以.jpg结尾的
        String ext = "*.jpg";
        Path fileTree = Paths.get("D:/temp/");
        Search search = new Search(ext);
        EnumSet<FileVisitOption> options = EnumSet.of(FileVisitOption.FOLLOW_LINKS);
        try {
            Files.walkFileTree(fileTree, options, Integer.MAX_VALUE, search);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
class Search implements FileVisitor {
    private PathMatcher matcher;
    public Search(String ext) {
        this.matcher = FileSystems.getDefault().getPathMatcher("glob:" + ext);
    }

    public void judgeFile(Path file) throws IOException {
        Path name = file.getFileName();
        if (name != null && matcher.matches(name)) {
            // 文件名匹配
            System.out.println("匹配的文件名: " + name);
        }
    }
    // 访问目录前调用
    @Override
    public FileVisitResult preVisitDirectory(Object dir, BasicFileAttributes attrs) throws IOException {
        return FileVisitResult.CONTINUE;
    }
    // 访问文件时调用
    @Override
    public FileVisitResult visitFile(Object file, BasicFileAttributes attrs) throws IOException {
        judgeFile((Path) file);
        return FileVisitResult.CONTINUE;
    }
    // 访问文件失败后调用
    @Override
    public FileVisitResult visitFileFailed(Object file, IOException exc) throws IOException {
        return FileVisitResult.CONTINUE;
    }
    // 访问一个目录后调用
    @Override
    public FileVisitResult postVisitDirectory(Object dir, IOException exc) throws IOException {
        System.out.println("postVisit: " + (Path) dir);
        return FileVisitResult.CONTINUE;
    }
}

运行结果:

匹配的文件名: d.jpg
postVisit: D:\temp\test
postVisit: D:\temp

Java的IO包

  • Java读写文件,只能以数据流的形式进行读写
  • java.io包中
  • 节点类:直接对文件进行读写
  • 包装类:
  • 1、转换类:字节 / 字符 / 数据类型的转化类 。
  • 2、装饰类:装饰节点类。

节点类

  • 直接操作文件类
  • InputStream,OutStream(字节)
  • FileInputStream , FileOutputStream
  • Reader , Writer(字符)
  • FileReader , FileWriter

转换类

  • 从字符到字节之间的转化
  • InputStreamReader: 文件读取时字节,转化为Java能理解的字符
  • OutputStreamWriter: Java将字符转化为字节输入到文件中

装饰类

  • DataInputStream , DataOutputStream :封装数据流
  • BufferedInputStream ,BufferOutputStream:缓存字节流
  • BufferedReader , BufferedWriter:缓存字符流

文本文件的读写

写操作


public static void main(String[] args) {
    writeFile();
}

public static void writeFile(){
    try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("D:/temp/demo3.txt")))) {
        bw.write("hello world");
        bw.newLine();
        bw.write("Java Home");
        bw.newLine();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Demo3.txt文件内容

hello world
Java Home

读操作


public static void main(String[] args) {
    readerFile();
}

private static void readerFile() {
    String line = "";
    try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("D:/temp/demo3.txt")))) {
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

运行结果:

hello world
Java Home

二进制文件读写java


public static void main(String[] args) {
    writeFile();
}

private static void writeFile() {
    try (DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("D:/temp/test.dat")))) {
        dos.writeUTF("hello");
        dos.writeUTF("hello world is test bytes");
        dos.writeInt(20);
        dos.writeUTF("world");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

文件内容

hellohello world is test bytes world

读操作


public static void main(String[] args) {
   readFile();
}

private static void readFile() {
    try (DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream("D:/temp/test.dat")))) {
        System.out.println(in.readUTF() + in.readUTF() + in.readInt() + in.readUTF());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

运行结果:

hellohello world is test bytes20world

ZIP文件的读写

  • zip文件操作类:java.util.zip包中
  • java.io.InputStream , java.io.OutputStream的子类
  • ZipInputStream , ZipOutputStream压缩文件输入 / 输出流
  • ZipEntry压缩项

多个文件压缩


// 多个文件压缩
public static void main(String[] args) {
    zipFile();
}
public static void zipFile() {
    File file = new File("D:/temp");
    File zipFile = new File("D:/temp.zip");
    FileInputStream input = null;
    try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile))) {
        // 添加注释
        zos.setComment(new String("多个个文件压缩".getBytes(),"UTF-8"));

        // 压缩过程
        int temp = 0;
        // 判断是否为文件夹
        if (file.isDirectory()) {
            File[] listFile = file.listFiles();
            for (int i = 0; i < listFile.length; i++) {
                    // 定义文件的输出流
                    input = new FileInputStream(listFile[i]);
                    // 设置Entry对象
                    zos.putNextEntry(new ZipEntry(file.getName() +
                            File.separator + listFile[i].getName() ));
                    System.out.println("正在压缩: " + listFile[i].getName());
                    // 读取内容
                    while ((temp = input.read()) != -1) {
                        // 压缩输出
                        zos.write(temp);
                    }
                    // 关闭输入流
                    input.close();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

注意:压缩的文件夹不能有子目录,否则会报FileNotFoundException: D:\temp\test (拒绝访问。),这是由于input = new FileInputStream(listFile[i]);读取的文件类型是文件夹导致的

多个文件解压缩


// 多个文件解压缩
public static void main(String[] args) throws Exception{
    // 待解压的zip文件,需要在zip文件上构建输入流,读取数据到Java中
    File file = new File("C:\\Users\\Wong\\Desktop\\test.zip");

    // 输出文件的时候要有文件夹的操作
    File outFile = null;
    // 实例化ZipEntry对象
    ZipFile zipFile = new ZipFile(file);

    // 定义解压的文件名
    OutputStream out = null;
    // 定义输入流,读取每个Entry
    InputStream input = null;
    // 每一个压缩Entry
    ZipEntry entry = null;
    
    // 定义压缩输入流,实例化ZipInputStream
    try (ZipInputStream zipInput = new ZipInputStream(new FileInputStream(file))) {
        // 遍历压缩包中的文件
        while ((entry = zipInput.getNextEntry()) != null) {
            System.out.println("解压缩 " + entry.getName().replaceAll("/", "") + " 文件");
            // 定义输出的文件路径
            outFile = new File("D:/" + entry.getName());
            
            boolean outputDirectoryNotExsits = !outFile.getParentFile().exists();
            // 当输出文件夹不存在时
            if (outputDirectoryNotExsits) {
                // 创建输出文件夹
                outFile.getParentFile().mkdirs();
            }
            
            boolean outFileNotExists = !outFile.exists();
            // 当输出文件不存在时
            if (outFileNotExists) {
                if (entry.isDirectory()) {
                    outFile.mkdirs();
                } else {
                    outFile.createNewFile();
                }
            }

            boolean entryNotDirctory = !entry.isDirectory();
            if (entryNotDirctory) {
                input = zipFile.getInputStream(entry);
                out = new FileOutputStream(outFile);
                int temp = 0;
                while ((temp = input.read()) != -1) {
                    out.write(temp);
                }
                input.close();
                out.close();
                System.out.println("解压缩成功");
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

到此这篇关于Java文件基本操作总结的文章就介绍到这了,更多相关Java文件基本操作内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: Java文件基本操作总结

本文链接: https://www.lsjlt.com/news/128657.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Java文件基本操作总结
    File文件类 java.io.File是文件和目录的重要类(JDK6及以前是唯一) 目录也使用File类进行表示 File类与操作系统无关,但会受到操作系...
    99+
    2022-11-12
  • Python文件与文件夹常见基本操作总结
    本文实例讲述了Python文件与文件夹常见基本操作。分享给大家供大家参考,具体如下: 1、判断文件(夹)是否存在。 os.path.exists(pathname) 2、判断路径名是否为文件。 ...
    99+
    2022-06-04
    文件夹 常见 操作
  • java IO 文件操作方法总结
    java IO 文件操作方法总结对于输入输出的理解:    输入输出,以程序为参考点,外部数据进入程序,通过输入流完成。程序将数据给外部设备,通过输出流完成。文件Io的操作//获取文件File file=new...
    99+
    2023-05-31
    java io
  • Java日期相关API的基本操作总结
    目录前言JDK8之前Date对象的使用格式化日期SimpleDateFormat类的使用JDK8之后LocalDate 、LocalTime 、LocalDateTime的使用格式化...
    99+
    2022-11-21
    Java日期API操作 Java日期API
  • python csv一些基本操作总结
    一、读取数据 csv.reader csv.reader传入的可以是列表或者文件对象,返回的是一个可迭代的对象,需要使用for循环遍历 path = "C:\\Users\\A539\\Desktop\\1.c...
    99+
    2022-06-02
    Python csv基本操作 csv模块的使用
  • 总结ElasticSearch基本操作!非常详细!
    es下载地址IK分词器下载地址索引创建索引 对比关系型数据库,创建索引就等同创建数据库 PUT请求 http://127.0.0.1:9200/shopping查询索引 GET请求 http://127.0.0.1:9200/...
    99+
    2023-05-14
    ElasticSearch
  • PyTorch学习之软件准备与基本操作总结
    目录一、概述二、工具准备三、conda命令四、PyTorch的安装五、Jupyter修改默认路径一、概述 PyTorch可以认为是一个Python库,可以像NumPy、Pandas一...
    99+
    2022-11-12
  • Python 文件操作方法总结
    目录文件处理流程基本操作打开文件 读文件内容关闭文件写文件文件处理流程 1.打开文件,得到文件句柄并赋值给一个变量2.通过句柄对文件进行操作3.关闭文件  r模式...
    99+
    2022-11-11
  • 基于Properties类操作.properties配置文件方法总结
    目录一、properties文件二、Properties类Properties类使用详解概述常见方法写入读取遍历一、properties文件 Properties文件是java中很常...
    99+
    2022-11-12
  • 基本的文件操作
    什么是文件? 文件是操作系统为用户或应用程序提供的读写硬盘的虚拟单位,有了文件我们可以读取数据,没有文件的话应该去在硬盘上扣动机械手臂然后寻找数据 如何使用文件 1,打开文件 2,读写数据 3,保存 4,关闭文件 使用python控制文...
    99+
    2023-01-31
    操作 文件
  • 文件的基本操作
    假设文件名为:loga.txt        内容为:你说什么呢     1 -- open() 打开文件   参数1: 要打开的文件路径 + 文件名   参数2: 打开方式     r   ---- 只读模式,文本必须存在     ...
    99+
    2023-01-30
    操作 文件
  • Linux文件基本属性知识点总结
    Linux系统是一种典型的多用户系统,不同的用户处于不同的地位,拥有不同的权限。为了保护系统的安全性,Linux系统对不同的用户访问同一文件(包括目录文件)的权限做了不同的规定。 在Linux中我们可以使用ll或者l...
    99+
    2022-06-03
    Linux 文件 基本属性
  • Python 6种基本变量操作技巧总结
    目录前言变量赋值变量类型对象引用对象身份变量名保留字(关键字)前言 看到这里已经学习了创建各种 Python 数据类型的值。并且显示的值都是文字或常量值。 >>> ...
    99+
    2022-11-13
  • 数据库基本操作语法归纳总结
    关系型数据库:以表作为实体,以主键和外键关系作为联系的一种数据结构。主键:在关系型数据库中,用一个唯一的标识符来标志每一行,这个标识符就是主键。主键有两个特点:非空和不能重复。外键:在关系型数据库中,外键就是用来表达表与表之间的关系、联系,...
    99+
    2023-05-31
    数据库 语法
  • PHP操作文件的命令总结
    本篇内容主要讲解“PHP操作文件的命令总结”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“PHP操作文件的命令总结”吧!PHP 包含文件PHP include 和 require 语句在 PHP ...
    99+
    2023-06-04
  • Java如何对文件进行基本操作
    这篇文章给大家分享的是有关Java如何对文件进行基本操作的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。File文件类java.io.File是文件和目录的重要类(JDK6及以前是唯一)目录也使用File类进行表示...
    99+
    2023-06-20
  • MySQL基础操作总结_CRUD
    文章目录 1.新增 insert 1.1 单行数据+全列插入 1.2 多行数据+指定列插入 2.查询 select 2.1 全列查询 2.2 指定列查询 2.3 查询字段包含表达式 2.4 别名 2.5 去重:distinct 2.6 排序...
    99+
    2023-09-01
    mysql 数据库
  • python3 csv文件基本操作
    csv(Comma-Separated Values),也叫逗号分割值,如果你安装了excel,默认会用excel打开csv文件。 废话少说直接贴代码: import csv # 打开文件,用with打开可以不用去特意关闭file了,p...
    99+
    2023-01-31
    操作 文件 csv
  • Python3 文件(夹)基本操作
    相关模块 os os.path shutil pathlib(New in version 3.4) 基本操作 判断文件(夹)是否存在。 os.path.exists(pathname) # new pathlib.Path(pat...
    99+
    2023-01-31
    操作 文件
  • Python文件(夹)基本操作
    1、判断文件(夹)是否存在。os.path.exists(pathname)2、判断路径名是否为文件。os.path.isfile(pathname)3、判断路径名是否为目录。os.path.isdir(pathname)4、创建文件。os...
    99+
    2023-01-31
    操作 文件 Python
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作