当前位置: 首页 > news >正文

Java 流(Stream)、文件(File)和IO详解

一、Java IO 基础体系

Java IO 基于的概念,将数据传输抽象为 “流”,分为输入流(读取数据)和输出流(写入数据)。根据处理数据类型,可分为:

  1. 字节流:处理二进制数据,基类为InputStreamOutputStream
  2. 字符流:处理文本数据,基类为ReaderWriter

核心类层次结构:

InputStream / OutputStream
├── FileInputStream / FileOutputStream
├── BufferedInputStream / BufferedOutputStream
├── DataInputStream / DataOutputStream
└── ObjectInputStream / ObjectOutputStreamReader / Writer
├── FileReader / FileWriter
├── BufferedReader / BufferedWriter
└── InputStreamReader / OutputStreamWriter
 

二、文件操作与File

java.io.File类用于表示文件或目录的抽象路径,提供文件元数据操作(创建、删除、重命名等),但不直接处理文件内容。

常用方法示例:

import java.io.File;
import java.io.IOException;public class FileExample {public static void main(String[] args) {// 创建File对象File file = new File("example.txt");try {// 创建新文件if (file.createNewFile()) {System.out.println("文件创建成功");}// 文件信息查询System.out.println("文件是否存在: " + file.exists());System.out.println("文件大小: " + file.length() + " 字节");System.out.println("是否为目录: " + file.isDirectory());// 目录操作File dir = new File("mydir");if (dir.mkdir()) {System.out.println("目录创建成功");}// 列出目录内容File[] files = dir.listFiles();if (files != null) {for (File f : files) {System.out.println(f.getName());}}// 文件重命名File newFile = new File("new_example.txt");if (file.renameTo(newFile)) {System.out.println("文件重命名成功");}// 删除文件if (newFile.delete()) {System.out.println("文件删除成功");}} catch (IOException e) {e.printStackTrace();}}
}
 

三、字节流操作

1. 文件读写(FileInputStream/FileOutputStream

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;public class ByteStreamExample {public static void main(String[] args) {try (// 自动关闭资源的try-with-resources语句FileInputStream fis = new FileInputStream("input.txt");FileOutputStream fos = new FileOutputStream("output.txt")) {int byteRead;// 每次读取一个字节,返回-1表示文件末尾while ((byteRead = fis.read()) != -1) {fos.write(byteRead);}System.out.println("文件复制完成");} catch (IOException e) {e.printStackTrace();}}
}
 

2. 带缓冲的字节流(BufferedInputStream/BufferedOutputStream

通过缓冲区减少系统 IO 调用,提升性能:
import java.io.*;public class BufferedByteStreamExample {public static void main(String[] args) {try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream("input.txt"));BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("output.txt"))) {byte[] buffer = new byte[8192];  // 8KB缓冲区int bytesRead;while ((bytesRead = bis.read(buffer)) != -1) {bos.write(buffer, 0, bytesRead);}} catch (IOException e) {e.printStackTrace();}}
}
 

四、字符流操作

1. 文件读写(FileReader/FileWriter

 
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;public class CharacterStreamExample {public static void main(String[] args) {try (FileReader reader = new FileReader("input.txt");FileWriter writer = new FileWriter("output.txt")) {int charRead;while ((charRead = reader.read()) != -1) {writer.write(charRead);}} catch (IOException e) {e.printStackTrace();}}
}
 

2. 带缓冲的字符流(BufferedReader/BufferedWriter

import java.io.*;public class BufferedCharacterStreamExample {public static void main(String[] args) {try (BufferedReader br = new BufferedReader(new FileReader("input.txt"));BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"))) {String line;// 逐行读取while ((line = br.readLine()) != null) {bw.write(line);bw.newLine();  // 写入换行符}} catch (IOException e) {e.printStackTrace();}}
}
 

五、Java NIO 与 Path API(Java 7+)

Java NIO(New IO)提供更高效的非阻塞 IO 操作,引入PathPathsFiles类简化文件操作。

1. Path 与 Files 类基础

import java.nio.file.*;public class NIOExample {public static void main(String[] args) {try {// 创建Path对象Path path = Paths.get("example.txt");// 读取文件内容(一次性读取所有行)byte[] bytes = Files.readAllBytes(path);String content = new String(bytes);// 写入文件String data = "Hello, NIO!";Files.write(path, data.getBytes());// 文件复制Path source = Paths.get("source.txt");Path target = Paths.get("target.txt");Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);// 目录操作Path dir = Paths.get("newdir");Files.createDirectory(dir);// 遍历目录try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {for (Path entry : stream) {System.out.println(entry.getFileName());}}} catch (IOException e) {e.printStackTrace();}}
}
 

2. 异步文件操作(Java 7+)

 
import java.nio.file.*;
import java.util.concurrent.*;public class AsyncFileExample {public static void main(String[] args) {Path path = Paths.get("large_file.txt");// 异步读取文件CompletableFuture.runAsync(() -> {try {byte[] data = Files.readAllBytes(path);System.out.println("文件读取完成,大小: " + data.length + " 字节");} catch (IOException e) {e.printStackTrace();}});// 主线程继续执行其他任务System.out.println("主线程继续执行...");}
}
 

六、Java 8 Stream API 与文件处理

Java 8 引入的 Stream API 简化了集合与 IO 操作,结合Files.lines()可高效处理大文件。

1. 逐行处理大文件

 
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;public class StreamFileExample {public static void main(String[] args) {Path path = Paths.get("large_file.txt");try (var lines = Files.lines(path)) {  // 自动关闭流lines.filter(line -> line.contains("keyword"))  // 过滤包含关键字的行.limit(10)  // 取前10条.forEach(System.out::println);  // 打印结果} catch (IOException e) {e.printStackTrace();}}
}
 

2. 并行处理文件内容

 
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;public class ParallelStreamExample {public static void main(String[] args) {Path path = Paths.get("large_file.txt");try (var lines = Files.lines(path)) {lines.parallel()  // 转换为并行流.filter(line -> line.length() > 100)  // 过滤长文本行.map(String::toUpperCase)  // 转换为大写.forEach(System.out::println);} catch (IOException e) {e.printStackTrace();}}
}
 

七、序列化与对象 IO

Java 提供对象序列化机制,允许将对象转换为字节流存储或传输。

1. 序列化对象

 
import java.io.*;// 实现Serializable接口
class Person implements Serializable {private static final long serialVersionUID = 1L;private String name;private int age;public Person(String name, int age) {this.name = name;this.age = age;}// Getters and setterspublic String getName() { return name; }public int getAge() { return age; }
}public class SerializationExample {public static void main(String[] args) {// 序列化try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person.ser"))) {Person person = new Person("Alice", 30);oos.writeObject(person);} catch (IOException e) {e.printStackTrace();}// 反序列化try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.ser"))) {Person restoredPerson = (Person) ois.readObject();System.out.println("Name: " + restoredPerson.getName());System.out.println("Age: " + restoredPerson.getAge());} catch (IOException | ClassNotFoundException e) {e.printStackTrace();}}
}
http://www.jsqmd.com/news/452812/

相关文章:

  • 打开网站显示596 Configuration pull failed 配置拉取失败错误怎么办|已解决
  • 话费卡回收渠道推荐:如何快速找到可靠的回收平台? - 团团收购物卡回收
  • 打开网站显示521 Web server is down 源站已关闭错误怎么办|已解决
  • 打开网站显示523 Origin is unreachable 无法访问源站错误怎么办|已解决
  • 加油卡回收平台怎么选?推荐高口碑平台及注意事项 - 团团收购物卡回收
  • 【节点】[SceneColor节点]原理解析与实际应用
  • 12、Tcp和udp,三次握手四次挥手
  • 11、文字编码ARP协议
  • 工业液位变送器优质厂家推荐指南:差压变送器、投入式液位计、插入式密度计、智能变送器、检测密度计、水位液位计选择指南 - 优质品牌商家
  • 2026工业液位仪表优质品牌推荐榜 - 优质品牌商家
  • 新手必看!这3款公众号编辑器绝了丨5分钟搞定微信公众号图文的排版编辑 - 小小智慧树~
  • 关于Unity中TimeLine的使用
  • 沃尔玛购物卡回收哪家强?三大优质平台大揭秘 - 京顺回收
  • JVM--8-深入JVM垃圾回收:从垃圾识别到回收算法 - 实践
  • 机票商旅返现是什么意思?2026高性价比商旅平台推荐,省钱攻略在此! - 匠言榜单
  • 900亿风投教父的终极警告:软件不再卖给人,270亿估值的Cursor快“死”了
  • NIO:解开非阻塞I/O高并发编程的秘密
  • 2026年口碑好的无锡电子画册厂家推荐:无锡大气商务画册厂家综合实力参考(2025) - 品牌宣传支持者
  • 2026年靠谱的RTP管品牌推荐:玻纤增强RTP管采购指南厂家怎么选 - 品牌宣传支持者
  • 最专业的加油卡回收平台推荐:靠谱吗?深度评测 - 团团收购物卡回收
  • 关于Unity游戏制作中遇到的一些问题
  • 加油卡如何回收?平台优劣势详细对比指南 - 团团收购物卡回收
  • 上周热点回顾(3.2
  • 盘点加油卡回收平台选择攻略:哪家最靠谱? - 团团收购物卡回收
  • 如何选择优质加油卡回收平台?避坑技巧全解析 - 团团收购物卡回收
  • 基于Microsoft.Extensions.AI 和 Microsoft.Extensions.VectorData构建向量搜索
  • Windows 系统下 JDK 1.8 + Tomcat 安装与配置
  • 农产品实名收购系统功能说明之电子秤已支持类型和厂家型号
  • 基于Java开发的大学社团管理系统源码+运行步骤+计算机技术
  • MySQL 常用内置函数与高级查询技巧,看这一篇就够了!