Heim  >  Artikel  >  Java  >  So führen Sie grundlegende Operationen an Dateien in Java durch

So führen Sie grundlegende Operationen an Dateien in Java durch

PHPz
PHPznach vorne
2023-04-29 17:13:061335Durchsuche

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<Path> listDirectory = Files.newDirectoryStream(path);
        for (Path path2 : listDirectory) {
            System.out.println(path2.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();
    }
}

Das obige ist der detaillierte Inhalt vonSo führen Sie grundlegende Operationen an Dateien in Java durch. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Dieser Artikel ist reproduziert unter:yisu.com. Bei Verstößen wenden Sie sich bitte an admin@php.cn löschen