Java 文件
最后修改于 2024 年 1 月 27 日
Java 文件教程展示了如何在 Java 中处理文件。我们创建一个文件,查找其大小,复制文件,删除文件,重命名文件,从文件读取数据,写入文件数据,并使用 Java Files
获取文件所有者。
Files
包含用于在 Java 语言中处理文件的静态方法。
Path
是一个用于在文件系统中定位文件的对象。 路径形成一个层次结构,由一系列目录和文件名元素组成,这些元素由特殊的分隔符或定界符分隔。 可以使用 Paths.get
和 File.toPath
方法创建 Path
。
Assasin bug, Avondale spider, Backswimmer, Bamboo moth, Banana moth, Bed bug, Black cocroach, Blue moon, Bumble Bee, Carpenter Bee, Cattle tick, Cave Weta, Cicada, Cinnibar, Click beetle, Clothes moth, Codling moth, Centipede, Earwig, Eucalypt longhorn beetle, Field Grasshopper, Garden slug, Garden soldier, German cockroach, German wasp, Giant dragonfly, Giraffe weevil, Grass grub, Grass looper, Green planthopper, Green house spider, Gum emperor, Gum leaf skeletoniser, Hornet, Mealybug, Mites, Mole Cricket, Monarch butterfly, Mosquito, Silverfish, Wasp, Water boatman, Winged weta, Wolf spider, Yellow Jacket, Yellow Admiral
这是一个示例文本文件,您可以在应用程序中使用它。
Java 创建文件
以下示例使用 Files.createFile
创建一个新文件。
package com.zetcode; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.FileAttribute; import java.nio.file.attribute.PosixFilePermission; import java.nio.file.attribute.PosixFilePermissions; import java.util.HashSet; import java.util.Set; public class JavaCreateFile { public static void main(String[] args) throws IOException { Set<PosixFilePermission> perms = new HashSet<>(); perms.add(PosixFilePermission.OWNER_READ); perms.add(PosixFilePermission.OWNER_WRITE); perms.add(PosixFilePermission.GROUP_READ); perms.add(PosixFilePermission.GROUP_WRITE); perms.add(PosixFilePermission.OTHERS_READ); FileAttribute<Set<PosixFilePermission>> attrs = PosixFilePermissions.asFileAttribute(perms); Path myPath = Paths.get("src/resources/myfile.txt"); if (Files.exists(myPath)) { System.out.println("File already exists"); } else { Files.createFile(myPath, attrs); System.out.println("File created"); } } }
我们使用 PosixFilePermission
设置新创建文件的文件权限。
Set<PosixFilePermission> perms = new HashSet<>(); perms.add(PosixFilePermission.OWNER_READ); perms.add(PosixFilePermission.OWNER_WRITE); perms.add(PosixFilePermission.GROUP_READ); perms.add(PosixFilePermission.GROUP_WRITE); perms.add(PosixFilePermission.OTHERS_READ);
在这里,我们选择文件的权限。
Path myPath = Paths.get("src/resources/myfile.txt");
使用 Paths.get
,我们获取文件的 Path
。
if (Files.exists(myPath)) {
在创建文件之前,我们使用 Files.exists
检查它是否存在。 如果我们尝试创建现有文件,则会抛出 FileAlreadyExistsException
。
Files.createFile(myPath, attrs);
使用 Files.createFile
创建文件。 它采用文件的 Path
和文件属性列表作为参数。
Java 文件大小
Files.size
确定文件的大小(以字节为单位)。
package com.zetcode; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class JavaFileSize { public static void main(String[] args) throws IOException { Path myPath = Paths.get("src/resources/bugs.txt"); long fileSize = Files.size(myPath); System.out.format("File size: %d bytes%n", fileSize); } }
该示例返回文本文件的大小。
Java 复制文件
Files.copy
复制文件。
package com.zetcode; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.StandardCopyOption; public class JavaCopyFile { public static void main(String[] args) throws IOException { var source = new File("src/resources/bugs.txt"); var dest = new File("src/resources/bugs2.txt"); Files.copy(source.toPath(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING); } }
在此示例中,我们复制一个文件。
Files.copy(source.toPath(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING);
Files.copy
采用以下参数:源文件的路径,目标文件的路径和复制选项。 如果目标文件已存在,StandardCopyOption.REPLACE_EXISTING
会导致目标文件被替换。
Java 删除文件
如果文件存在,Files.deleteIfExists
会删除该文件。
package com.zetcode; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class JavaDeleteFile { public static void main(String[] args) throws IOException { Path myPath = Paths.get("src/resources/myfile.txt"); boolean fileDeleted = Files.deleteIfExists(myPath); if (fileDeleted) { System.out.println("File deleted"); } else { System.out.println("File does not exist"); } } }
该示例删除一个文件。
boolean fileDeleted = Files.deleteIfExists(myPath);
Files.deleteIfExists
删除一个文件,如果该文件已删除则返回 true,如果由于该文件不存在而无法删除,则返回 false。
Java 移动文件
使用 Files.move
重命名文件。
package com.zetcode; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class JavaMoveFile { public static void main(String[] args) throws IOException { Path myPath = Paths.get("src/resources/myfile.txt"); Path myPath2 = Paths.get("src/resources/myfile2.txt"); Files.move(myPath, myPath2); System.out.println("File moved"); } }
该示例重命名一个文件。
Files.move(myPath, myPath2);
Files.move
采用两个参数:源文件路径和目标文件路径。
Java 读取文件
Files.readAllLines
从文件中读取所有行。 它确保在读取所有字节或抛出异常时正确关闭文件。
Files.readAllLines
不适合读取大型文件。
package com.zetcode; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; public class JavaReadFile { public static void main(String[] args) throws IOException { Path myPath = Paths.get("src/resources/bugs.txt"); List<String> lines = Files.readAllLines(myPath, StandardCharsets.UTF_8); lines.forEach(line -> System.out.println(line)); } }
该示例读取文本文件并将其内容写入控制台。
List<String> lines = Files.readAllLines(myPath, StandardCharsets.UTF_8);
Files.readAllLines
采用文件路径和字符集作为参数。
lines.forEach(line -> System.out.println(line));
使用 forEach
,我们遍历列表并打印所有行。
Java 写入文件
Files.write
将文本行写入文件。 该方法确保最终正确关闭文件。
package com.zetcode; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.List; public class JavaWriteFile { public static void main(String[] args) throws IOException { Path myPath = Paths.get("src/resources/myfile.txt"); List<String> lines = new ArrayList<>(); lines.add("blue sky"); lines.add("sweet orange"); lines.add("fast car"); lines.add("old book"); Files.write(myPath, lines, StandardCharsets.UTF_8, StandardOpenOption.CREATE); System.out.println("Data written"); } }
在此示例中,我们将四个文本行写入文件。
Files.write(myPath, lines, StandardCharsets.UTF_8, StandardOpenOption.CREATE);
Files.write
采用文件路径,字符集和文件打开选项作为参数。 使用 StandardOpenOption.CREATE
,如果文件不存在,则会创建该文件。
Java 文件所有者
Files.getOwner
返回文件的所有者。
package com.zetcode; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.UserPrincipal; public class JavaGetFileOwner { public static void main(String[] args) throws IOException { Path myPath = Paths.get("src/resources/bugs.txt"); UserPrincipal userPrincipal = Files.getOwner(myPath); String owner = userPrincipal.getName(); System.out.println(owner); } }
在此示例中,我们获取文件的所有者。
来源
在本文中,我们使用 Files
完成了一些基本的文件操作。
作者
列出所有Java教程。