千家信息网

Java怎么对文件进行基本操作

发表于:2026-11-01 作者:千家信息网编辑
千家信息网最后更新 2026年11月01日,这篇文章主要介绍"Java怎么对文件进行基本操作",在日常操作中,相信很多人在Java怎么对文件进行基本操作问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答"Java怎么对
千家信息网最后更新 2026年11月01日Java怎么对文件进行基本操作

这篇文章主要介绍"Java怎么对文件进行基本操作",在日常操作中,相信很多人在Java怎么对文件进行基本操作问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答"Java怎么对文件进行基本操作"的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

File文件类

  • java.io.File是文件和目录的重要类(JDK6及以前是唯一)

  • 目录也使用File类进行表示

  • File类与操作系统无关,但会受到操作系统的权限限制

  • 常用方法

  • createNewFile , delete , exists , getAbsolutePath , getName , getParent , getPath

  • isDirectory , 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 path2 = file.toPath();    System.out.println(path.compareTo(path2)); // 结果为0 说明两个path相等    // 获取Path方法三    Path path4 = 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 path3 = path.resolve("a.java");        Path path4 = path.resolve("b.java");        Path path5 = path.resolve("c.txt");        Path path6 = path.resolve("d.jpg");        Files.createFile(path3);        Files.createFile(path4);        Files.createFile(path5);        Files.createFile(path6);        // 不带条件的遍历输出        DirectoryStream listDirectory = Files.newDirectoryStream(path);        for (Path path2 : listDirectory) {            System.out.println(path2.getFileName());        }        // 创建一个带有过滤器,过滤文件名以java txt结尾的文件        DirectoryStream 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 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怎么对文件进行基本操作"的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注网站,小编会继续努力为大家带来更多实用的文章!

文件 目录 输出 文件夹 字符 输入 多个 字节 文件名 方法 结果 基本操作 内容 数据 学习 移动 运行 对象 属性 系统 数据库的安全要保护哪些东西 数据库安全各自的含义是什么 生产安全数据库录入 数据库的安全性及管理 数据库安全策略包含哪些 海淀数据库安全审计系统 建立农村房屋安全信息数据库 易用的数据库客户端支持安全管理 连接数据库失败ssl安全错误 数据库的锁怎样保障安全 南京欣网互联网络科技有限公司 蓝思科技飞鸽互联网 广州百单互联网科技有限公司 互联网最新的科技 河南真二互联网科技有限公司 互联网与未来科技 天津摩尔互联网科技 无线互联网科技 创业天下互联网科技有限公司 银川新华互联网科技职业技术培训学校图片 重庆互联网医院沙龙医盟信息科技 花神(南京)互联网科技有限公司 互联网5g黑科技有哪些 广州市恰铎互联网科技有限公司 明优互联网科技有限公司 互联网方面的科技前沿 上海创道互联网络科技有限公司 深圳互联网科技园地址 东风日产互联网科技公司叫什么 现代科技的标志之一的互联网 互联网科技网 赫美联合互联网科技 互联网科技大会 南山科技园互联网公司有哪些 互联网科技创新服务 消费医药和互联网科技 特约风豹互联网科技为什么扣费 山东星卡互联网科技有限公司官网 富国互联网金融科技混合基金 知域互联网科技有限公司官网
0