文件I/O

Path

resolve                 拼接路径
normalize 格式化
getFileName 获取文件名
getNameCount 获取路径段个数
getName(0) 获取指定路径段的名称
getParent 获取父级目录 Path path = Paths.get("C:\\Users\\26401\\Desktop\\");
Path path1 = Paths.get("demo.txt");
path.resolve(path1).normalize().toString(); // "file:///C:/Users/26401/Desktop/demo.txt"

Files

Path path = Paths.get("C:\\Users\\26401\\Desktop\\demo.txt");
Files.exists(path);
Files.notExists(path);
Files.isDirectory(path); // 是否是目录
Files.isRegularFile(path); // 是否是文件
Files.isReadable(path); // 是否可读
Files.isWritable(path); // 是否可写
Files.isExecutable(path); // 是否可执行
Files.isHidden(path); // 是否可隐藏
Files.probeContentType(path);// 获取MIME类型
Files.readAllLines(path, StandardCharsets.UTF_8); // 读取所有行 List<String> lines = Arrays.asList("First line", "Second line", "Third line");
Files.write(path, lines); // 一行行写 byte[] data = Files.readAllBytes(path); // 读取所有字节

File类

String separator = File.pathSeparator;                                      // 文件路径分隔符
String separator = File.separator; // 文件名分隔符 File file = new File("C:\\Users\\26401\\Desktop\\java");
File file = new File("C:\\Users\\26401\\Desktop\\java", "demo.txt"); File fileFather = new File("C:\\Users\\26401\\Desktop\\java");
File file = new File(fileFather, "demo.txt"); try {
boolean b = file.createNewFile(); // 创建文件
boolean b = file.mkdir(); // 创建文件夹
boolean b = file.mkdirs(); // 创建多级文件夹
boolean b = file.delete(); // 删除文件或者文件夹
String s = file.getName(); // 获取文件或者文件夹名
String s = file.getPath(); // 获取文件或者文件夹路径
long s = file.length(); // 获取文件大小
String s = file.getAbsolutePath(); // 获取文件或者文件夹绝对路径
File s = file.getAbsoluteFile(); // 获取文件或者文件夹绝对路径
File s = file.getParentFile(); // 获取文件或者文件夹父路径
boolean b = file.exists(); // 判断文件或者文件夹是否存在
boolean b = file.isDirectory(); // 判断文件夹是否存在
boolean b = file.isFile(); // 判断文件是否存在
String[] arr = file.list(); // 获取文件夹下的文件名和文件夹名
File[] arr = file.listFiles(); // 获取文件夹下的文件和文件夹
} catch (Exception e) {
e.printStackTrace();
}

File和Path的区别和联系

文件路径操作
path:
Path path = new File("demo.txt").toPath();
file:
File file = Paths.get("demo.txt").toFile(); 删除文件
file:
file.delete();
path:
Files.deleteIfExists(path); 写数据
file:
FileOutputStream outputStream = new FileOutputStream(file);
outputStream.write("写入数据".getBytes(StandardCharsets.UTF_8)); path:
OutputStream outputStream = Files.newOutputStream(path, StandardOpenOption.WRITE);
outputStream.write("写入数据".getBytes(StandardCharsets.UTF_8)); 遍历目录
file:
for (File selectedFile : folder.listFiles()) {
System.out.println((selectedFile.isDirectory() ? "d" : "f") + " " + selectedFile.getAbsolutePath());
}
或者
DirectoryStream<Path> paths = Files.newDirectoryStream(Paths.get("...."));
for (Path path : paths) {
if (Files.isDirectory(path)) {
System.out.println(path.getFileName());
}
} path:
Files.walkFileTree(path, EnumSet.noneOf(FileVisitOption.class), 1, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path selectedPath, BasicFileAttributes attrs) throws IOException {
System.out.println("d " + selectedPath.toAbsolutePath());
return FileVisitResult.CONTINUE;
} @Override
public FileVisitResult visitFile(Path selectedPath, BasicFileAttributes attrs) throws IOException {
System.out.println("f " + selectedPath.toAbsolutePath());
return FileVisitResult.CONTINUE;
}
}); 正则
path:
Path dir = Paths.get(filepath);
PathMatcher imageFileMatcher = FileSystems.getDefault().getPathMatcher("regex:.*(?i:jpg|jpeg|png|gif|bmp|jpe|jfif)");
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, entry -> imageFileMatcher.matches(entry.getFileName()))) {
for (Path path : stream) {
System.out.println(path.getFileName());
}
} 读图片
file:
Image img = ImageIO.read(new File("demo.png"));

FileFilter

过滤文件
class myFilter implements FileFilter {
public boolean accept(File pathname) {
String name = pathname.getName();
return name.endsWith(".txt");
}
} File fileFather = new File("C:\\Users\\26401\\Desktop\\java");
File file = new File(fileFather, "demo");
try {
File[] arr = file.listFiles(new myFilter());
for (File file2 : arr) {
System.out.println(file2);
}
} catch (Exception e) {
e.printStackTrace();
}

FileOutputStream

写入数据

    FileOutputStream f = null;
try {
f = new FileOutputStream("C:\\Users\\26401\\Desktop\\java\\demo\\demo.txt"); // 创建并覆盖文件
f = new FileOutputStream("C:\\Users\\26401\\Desktop\\java\\demo\\demo.txt", true); // 续写文件流
f.write(100); // 写一个字节 byte[] bs = {49, 48, 48};
f.write(bs); // 写字节数组 f.write("abc".getBytes()); // 写字节数组 f.write("a\r\nb\r\nc".getBytes()); // \r\n换行
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(f != null) f.close();
} catch (IOException e) {
e.printStackTrace();
}
}

FileInputStream

读取数据

    一个一个字节读
try(FileInputStream f = new FileInputStream("C:\\Users\\26401\\Desktop\\java\\demo\\demo.txt")) {
int i;
while((i = f.read()) != -1) {
System.out.println((char)i);
}
} 利用字节数组缓冲区读
try(FileInputStream f = new FileInputStream("C:\\Users\\26401\\Desktop\\java\\demo\\demo.txt")) {
int len;
byte[] b = new byte[1024]; while((len = f.read(b)) != -1) {
System.out.println(new String(b, 0, len));
}
}

利用FileOutputStream和FileInputStream复制文件

try(
FileInputStream fi = new FileInputStream("C:\\Users\\26401\\Desktop\\java\\demo\\demo.txt");
FileOutputStream fo = new FileOutputStream("C:\\Users\\26401\\Desktop\\java\\demo\\demo1.txt")
) {
int len;
byte[] b = new byte[1024]; while((len = fi.read(b)) != -1) {
fo.write(b, 0, len);
}
}

FileWriter

try(FileWriter fo = new FileWriter("C:\\Users\\26401\\Desktop\\java\\demo\\demo1.txt")){
byte[] b = {'a', 'b', 'c'};
fo.write(new String(b, 0, 2, "UTF-8"));
}

FileReader

try(FileReader fo = new FileReader("C:\\Users\\26401\\Desktop\\java\\demo\\demo1.txt")){
char[] b = new char[1];
while((fo.read(b)) != -1) {
System.out.println(new String(b));
}
}

BufferedWriter

Path path = Paths.get("C:\\Users\\26401\\Desktop\\demo.txt");
String str = "写入一行数据"; try (BufferedWriter bw = Files.newBufferedWriter(path)) {
bw.write(str);
bw.newLine();
bw.write(str);
bw.flush();
} 或者是BufferedWriter bw = new BufferedWriter(new FileWriter("path"));

BufferedReader

基本用法

try (BufferedReader br = Files.newBufferedReader(path)) {
char[] b = new char[20];
while((br.read(b)) != -1) {
System.out.println(new String(b));
}
} 或者是BufferedReader br = new BufferedReader(new FileReader("path")); BufferedReader 用来读字符,可以一次读一行 用法一
int ch;
while ((ch = br.read()) != -1) {
...
} 用法二
String line = null;
while ((line = reader.readLine) != null) {
...
} 用法三
按行生成集合
br.lines().collect(Collectors.toList());

StringWriter

StringWriter writer = new StringWriter();
char[] ary = new char[1024];
BufferedReader buffer = new BufferedReader(new InputStreamReader(new FileInputStream("...");, "UTF-8"));
int x;
while ((x = buffer.read(ary)) != -1) {
writer.write(ary, 0, x);
}
writer.toString();

InputStreams转换成字符串

StringWriter writer = new StringWriter();
char[] buffer = new char[1024];
try (Reader reader = new BufferedReader(new InputStreamReader(new FileInputStream("C:\\Users\\26401\\Desktop\\demo.txt"), "UTF-8"))) {
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
}
writer.toString();

BufferedInputStream

try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream("..."))) {
byte data;
while ((data = (byte) bis.read()) != -1) {
System.out.println((char) data);
}
} catch (IOException e) {
e.printStackTrace();
}

ObjectOutputStream

序列化对象

    class Demo implements Serializable {
String Name;
int Age;
static transient String Sex; // transient禁止实例序列化,static是类属性,实例无法序列化
static final long serialVersionUID = 1243543523L; // 自定义类唯一序列号标识
public void fn() {
System.out.println(this.Name + "|" + this.Age + "|" + this.Sex);
}
public Demo(String Name, int Age, String Sex) {
this.Name = Name;
this.Age = Age;
this.Sex = Sex;
}
} try(
FileOutputStream fo = new FileOutputStream("C:\\Users\\26401\\Desktop\\java\\demo.txt");
ObjectOutputStream foo = new ObjectOutputStream(fo);
){
Demo d = new Demo("叶家伟", 18, "女");
foo.writeObject(d);
}

ObjectInputStream

反序列化对象

    try(
FileInputStream fi = new FileInputStream("C:\\Users\\26401\\Desktop\\java\\demo.txt");
ObjectInputStream fii = new ObjectInputStream(fi)
){
Demo d = (Demo)fii.readObject();
System.out.println(d.Age);
}

PrintWriter

用法一:

    try(
PrintWriter pw = new PrintWriter("C:\\Users\\26401\\Desktop\\java\\demo.txt")
){
pw.println("affsddfq");
pw.flush();
} 用法二: try(
FileOutputStream fo = new FileOutputStream("C:\\Users\\26401\\Desktop\\java\\demo.txt");
PrintWriter pw = new PrintWriter(fo)
){
pw.println("wrqr3");
pw.flush();
} 用法三: try(
FileOutputStream fo = new FileOutputStream("C:\\Users\\26401\\Desktop\\java\\demo.txt");
PrintWriter pw = new PrintWriter(fo, true); // 第二个参数,表示自动刷新,也就是可以省略flush语句
){
pw.println("wrqr3");
}

利用PrintWriter复制文件

try(
BufferedReader fo = new BufferedReader(new FileReader("C:\\Users\\26401\\Desktop\\java\\demo.txt"));
PrintWriter pw = new PrintWriter(new FileWriter("C:\\Users\\26401\\Desktop\\java\\demo1.txt"), true)
){
String line = null;
while((line = fo.readLine()) != null) {
pw.println(line);
}
}

PrintStream

写数据

try(PrintStream ps = new PrintStream(filepath)){
ps.println("...");
ps.println();
ps.println("I love Java!");
ps.printf("Today is: %1$tm/%1$td/%1$tY", LocalDate.now());
ps.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
}

Channel

配合Buffer读文件

FileInputStream fis = new FileInputStream("C:\\Users\\26401\\Desktop\\demo.txt");
FileChannel fileChannel = fis.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (fileChannel.read(buffer) > 0) {
buffer.flip(); // 重置指针位置
while (buffer.hasRemaining()) {
byte b = buffer.get();
System.out.print((char) b);
}
buffer.clear();
}
fileChannel.close();

写文件

FileOutputStream fos = new FileOutputStream(outputFile);
FileChannel fileChannel = fos.getChannel();
ByteBuffer buffer = ByteBuffer.wrap(text.getBytes());
fileChannel.write(buffer);

利用Channel复制文件

File sourceFile = new File("C:\\Users\\26401\\Desktop\\demo.txt");
File destFile = new File("C:\\Users\\26401\\Desktop\\demo1.txt");
if (!sourceFile.exists() || !destFile.exists()) {
System.out.println("Source or destination file doesn't exist");
}
try (
FileChannel sourceChannel = new FileInputStream(sourceFile).getChannel();
FileChannel destChanel = new FileOutputStream(destFile).getChannel()
) {
sourceChannel.transferTo(0, sourceChannel.size(), destChanel);
}

System.out和System.err流重定向

System.setOut(new PrintStream(new FileOutputStream(new File("C:\\Users\\26401\\Desktop\\demo.txt"))));
System.setErr(new PrintStream(new FileOutputStream(new File("C:\\Users\\26401\\Desktop\\demo1.txt"))));
System.out.println("输出数据1");
System.out.println("输出数据2");
System.err.println("错误数据1");
System.err.println("错误数据2");

访问zip文件

Path pathToZip = Paths.get("file.zip");
try(FileSystem zipFs = FileSystems.newFileSystem(pathToZip, null)) {
Path root = zipFs.getPath("/");
...
} catch(IOException ex) {
ex.printStackTrace();
}

创建

Map<String, String> env = new HashMap<>();
env.put("create", "true"); //required for creating a new zip file
env.put("encoding", "UTF-8"); //optional: default is UTF-8
URI uri = URI.create("jar:file:/path/to/file.zip");
try (FileSystem zipfs = FileSystems.newFileSystem(uri, env)) {
Path newFile = zipFs.getPath("/newFile.txt");
Files.write(newFile, "Hello world".getBytes());
} catch(IOException ex) {
ex.printStackTrace();
}

结语

本文章是java成神的系列文章之一

如果你想知道,但是本文没有的,请下方留言

我会第一时间总结出来并发布填充到本文

java成神之——文件IO的更多相关文章

  1. java成神之——Stream和Optional

    Stream流 基本使用 流关闭 平行流 流重用 iterator转换成流 分组计数 无限流 流转集合 压缩流 统计数值流 集合转换流遍历 流拼接 reduce 使用流生成随机字符串 流的包装流 几种 ...

  2. java成神之——properties,lambda表达式,序列化

    Properties 加载defaults.properties文件 写Properties到xml文件 读Properties从xml文件 Lambda表达式 自定义 内置 sort方法中使用Lam ...

  3. java成神之——ImmutableClass,null检查,字符编码,defaultLogger,可变参数,JavaScriptEngine,2D图,类单例,克隆,修饰符基本操作

    ImmutableClass null检查 字符编码 default logger 函数可变参数 Nashorn JavaScript engine 执行脚本文件 改变js文件输出流 全局变量 2D图 ...

  4. java成神之——注释修饰符

    注释修饰符 自定义注释 元注释 通过反射在runtime访问注释 内置注释 多注释实例 错误写法 使用容器改写 使用@Repeatable元注释 注释继承 使用反射获取注释 获取类的注释 获取方法的注 ...

  5. java成神之——java常识

    java常识 简单DOS命令 java基础名词 java编译和运行流程 Eclipse常用快捷键 Eclipse相关操作 java基本数据类型 java基本数据类型转换 java常用运算符 java流 ...

  6. 转载_2016,Java成神初年

    原文地址:http://blog.csdn.net/chenssy/article/details/54017826 2016,Java成神初年.. -------------- 时间2016.12. ...

  7. Java成神路上之设计模式系列教程之一

    Java成神路上之设计模式系列教程之一 千锋-Feri 在Java工程师的日常中,是否遇到过如下问题: Java 中什么叫单例设计模式?请用Java 写出线程安全的单例模式? 什么是设计模式?你是否在 ...

  8. java成神之——安全和密码

    安全和密码 加密算法 公钥和私钥加密解密 生成私钥和公钥 加密数据 解密数据 公钥私钥生成的不同算法 密钥签名 生成加密随机数 基本用法 指定算法 加密对象 SealedObject Signatur ...

  9. java成神之——网络编程基本操作

    网络编程 获取ip UDP程序示例 TCP程序 结语 网络编程 获取ip InetAddress id = InetAddress.getLocalHost(); // InetAddress id ...

随机推荐

  1. tflearn kears GAN官方demo代码——本质上GAN是先训练判别模型让你能够识别噪声,然后生成模型基于噪声生成数据,目标是让判别模型出错。GAN的过程就是训练这个生成模型参数!!!

    GAN:通过 将 样本 特征 化 以后, 告诉 模型 哪些 样本 是 黑 哪些 是 白, 模型 通过 训练 后, 理解 了 黑白 样本 的 区别, 再输入 测试 样本 时, 模型 就可以 根据 以往 ...

  2. IDEA配置 及 快捷键

    快捷键: 格式化代码 Ctrl+alt+L 后退Ctrl+alt+ <- 格式化代码快捷键:Ctrl + Alt + L 删除整行:Ctrl+X 实现类 ctrl + alt Ctrl+N 查找 ...

  3. input type=file 怎么样调取用户手机照相机

    input 有个属性accept="image/*" 这样就可以了,同时在网上看到了其他答案,试了下没啥效果.写记录下来 如下: 使用input:file标签, 去调用系统默认相机 ...

  4. ViewGroup的事件分发机制

    我们用手指去触摸Android手机屏幕,就会产生一个触摸事件,但是这个触摸事件在底层是怎么分发的呢?这个我还真不知道,这里涉及到操作硬件 (手机屏幕)方面的知识,也就是Linux内核方面的知识,我也没 ...

  5. CSS:Tutorial three

    1.CSS Links links can be styled differently depending on what state they are in. The four links stat ...

  6. 【python】没有root权限的时候安装Python package

    下载相关位置的包 1.首先在git上下载对应的包: 搜索package github,找到地址.使用 git clone https://xxx.git 命令 2.使用python setup.py ...

  7. build.prop文件介绍与用法举例

    build.prop 是一个属性文件,在Android系统中.prop文件很重要,记录了系统的设置和改变 以下是修改教程及一些build.prop参数的中英文对照解释,修改前,注意先备份原build. ...

  8. 剑指Offer(第二版)面试案例:树中两个节点的最低公共祖先节点

    (尊重劳动成果,转载请注明出处:http://blog.csdn.net/qq_25827845/article/details/74612786冷血之心的博客) 剑指Offer(第二版)面试案例:树 ...

  9. Arcgis for Javascript之featureLayer图和属性的互操作

    说明:主要实现加载FeatureLayer与显示属性表,并实现属性表与地图的联动,首先,看看实现后的效果: 显示效果 如上图所示,本文章主要实现了以下几个功能:1.FeatureLayer属性表的分页 ...

  10. InnoDB MVCC RR隔离级别下的数据可见性总结

    一.背景 熟悉数据库隔离级别的人都知道,在RR(可重复读)隔离级别下,无论何时多次执行相同的SELECT快照读语句,得到的结果集都是完全一样的,即便两次SELECT语句执行期间,其他事务已经改变了该查 ...