Java 基本语法详解(六)
十五、IO 流基础(文件读写操作)
IO(Input/Output)流用于处理设备间的数据传输(如文件读写、网络通信),Java 中 IO 流分为字节流(处理所有类型数据,如图片、视频)和字符流(仅处理文本数据,如.txt 文件),核心操作是 “读”(从外部到程序)和 “写”(从程序到外部)。
1. 字节流(InputStream/OutputStream)
字节流以 “字节” 为单位处理数据,顶层抽象类为InputStream(输入字节流)和OutputStream(输出字节流),常用实现类是FileInputStream(读文件)和FileOutputStream(写文件)。
(1)字节流写文件(FileOutputStream)
示例:向文件中写入文本内容(字节流可写任意类型数据,此处以文本为例)
import java.io.FileOutputStream;
import java.io.IOException;
public class FileOutputStreamDemo {
public static void main(String[] args) {
// 1. 声明流对象(try-with-resources语法:自动关闭流,无需手动close())
try (FileOutputStream fos = new FileOutputStream("D:\\test.txt")) {
// 2. 要写入的内容(字符串转字节数组)
String content = "Hello, IO Stream!";
byte[] bytes = content.getBytes(); // 字符串→字节数组
// 3. 写入文件(write()方法)
fos.write(bytes);
System.out.println("文件写入成功!");
} catch (IOException e) {
// 4. 捕获IO异常(如路径不存在、权限不足)
e.printStackTrace();
}
}
}
说明:
-
try-with-resources语法:流对象声明在try()中,代码执行后自动关闭流(需实现AutoCloseable接口),避免资源泄漏;
-
若文件不存在,FileOutputStream会自动创建文件;若文件已存在,默认覆盖内容(需追加内容时,用构造方法new FileOutputStream(“路径”, true))。
(2)字节流读文件(FileInputStream)
示例:读取文件中的内容并打印
import java.io.FileInputStream;
import java.io.IOException;
public class FileInputStreamDemo {
public static void main(String[] args) {
// try-with-resources声明流对象
try (FileInputStream fis = new FileInputStream("D:\\test.txt")) {
// 1. 创建字节数组(缓冲区,提升读取效率)
byte[] buffer = new byte[1024]; // 每次最多读1024字节
int len; // 记录每次实际读取的字节数(-1表示读完)
// 2. 循环读取文件内容
System.out.print("文件内容:");
while ((len = fis.read(buffer)) != -1) {
// 字节数组→字符串(仅读取实际有效长度len)
String content = new String(buffer, 0, len);
System.out.print(content);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
输出结果:
文件内容:Hello, IO Stream!
2. 字符流(Reader/Writer)
字符流以 “字符” 为单位处理文本数据,自动处理编码问题(如 UTF-8、GBK),顶层抽象类为Reader(输入字符流)和Writer(输出字符流),常用实现类是FileReader(读文本)和FileWriter(写文本)。
(1)字符流写文本(FileWriter)
示例:向文本文件写入内容(支持直接写字符串,无需转字节)
import java.io.FileWriter;
import java.io.IOException;
public class FileWriterDemo {
public static void main(String[] args) {
try (FileWriter fw = new FileWriter("D:\\test.txt", true)) { // true:追加内容
// 直接写入字符串(字符流特性)
fw.write("\n这是字符流写入的内容!");
fw.flush(); // 强制刷新缓冲区(字符流需手动刷新,否则可能不写入)
System.out.println("文本写入成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
说明:字符流内部有缓冲区,写入内容会先存到缓冲区,需调用flush()或关闭流(try-with-resources自动关闭)时才会真正写入文件。
(2)字符流读文本(FileReader)
示例:读取文本文件内容并打印
import java.io.FileReader;
import java.io.IOException;
public class FileReaderDemo {
public static void main(String[] args) {
try (FileReader fr = new FileReader("D:\\test.txt")) {
// 字符缓冲区(每次读1024字符)
char[] buffer = new char[1024];
int len;
System.out.print("文件内容:");
while ((len = fr.read(buffer)) != -1) {
// 字符数组→字符串
String content = new String(buffer, 0, len);
System.out.print(content);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
输出结果:
文件内容:Hello, IO Stream!
这是字符流写入的内容!
十六、日期时间处理(Java 8+ 新 API)
Java 8 前的Date、Calendar类存在线程不安全、API 设计混乱等问题,Java 8 引入java.time 包,提供了线程安全、易用的新日期时间 API,核心类包括LocalDate(日期)、LocalTime(时间)、LocalDateTime(日期时间)。
1. 核心类介绍
| 类名 | 功能描述 | 示例 |
|---|---|---|
| LocalDate | 仅表示日期(年 - 月 - 日) | 2025-11-06 |
| LocalTime | 仅表示时间(时:分: 秒) | 15:30:45 |
| LocalDateTime | 表示日期 + 时间(年 - 月 - 日 时:分: 秒) | 2025-11-06T15:30:45 |
| DateTimeFormatter | 日期时间格式化 / 解析器 | 自定义格式(如 yyyy-MM-dd HH:mm:ss) |
2. 常用操作示例
(1)获取当前日期时间
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
public class LocalDateTimeDemo1 {
public static void main(String[] args) {
// 1. 获取当前日期(LocalDate)
LocalDate currentDate = LocalDate.now();
System.out.println("当前日期:" + currentDate); // 输出:当前日期:2025-11-06
// 2. 获取当前时间(LocalTime)
LocalTime currentTime = LocalTime.now();
System.out.println("当前时间:" + currentTime); // 输出:当前时间:15:35:22.123(含毫秒)
// 3. 获取当前日期时间(LocalDateTime)
LocalDateTime currentDateTime = LocalDateTime.now();
System.out.println("当前日期时间:" + currentDateTime); // 输出:当前日期时间:2025-11-06T15:35:22.123
}
}
(2)日期时间格式化(DateTimeFormatter)
将LocalDateTime转为指定格式的字符串,或把字符串解析为LocalDateTime。
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class LocalDateTimeDemo2 {
public static void main(String[] args) {
// 1. 定义格式化器(指定格式:年-月-日 时:分:秒)
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
// 2. 日期时间→字符串(格式化)
LocalDateTime now = LocalDateTime.now();
String formattedDateTime = now.format(formatter);
System.out.println("格式化后的日期时间:" + formattedDateTime); // 输出:格式化后的日期时间:2025-11-06 15:40:30
// 3. 字符串→日期时间(解析)
String dateTimeStr = "2025-12-25 08:00:00";
LocalDateTime parsedDateTime = LocalDateTime.parse(dateTimeStr, formatter);
System.out.println("解析后的日期时间:" + parsedDateTime); // 输出:解析后的日期时间:2025-12-25T08:00
}
}
常用格式符:
-
yyyy:4 位年份(如 2025);
-
MM:2 位月份(如 11);
-
dd:2 位日期(如 06);
-
HH:24 小时制小时(如 15);
-
mm:2 位分钟(如 40);
-
ss:2 位秒(如 30)。
(3)日期时间计算(加减、比较)
LocalDateTime提供了便捷的方法进行日期时间增减和比较,无需手动处理月份天数、闰年等问题。
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class LocalDateTimeDemo3 {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
System.out.println("今天:" + today); // 输出:今天:2025-11-06
// 1. 日期加减(plusXxx() 加,minusXxx() 减)
LocalDate nextWeek = today.plusWeeks(1); // 加1周
LocalDate lastMonth = today.minusMonths(1); // 减1月
System.out.println("一周后:" + nextWeek); // 输出:一周后:2025-11-13
System.out.println("一个月前:" + lastMonth); // 输出:一个月前:2025-10-06
// 2. 计算两个日期的差值(ChronoUnit)
LocalDate birthday = LocalDate.of(2000, 5, 20); // 自定义日期
long daysBetween = ChronoUnit.DAYS.between(birthday, today); // 计算间隔天数
System.out.println("从生日到今天共:" + daysBetween + "天"); // 输出:从生日到今天共:9298天(示例值)
// 3. 日期比较(isBefore() 之前,isAfter() 之后,isEqual() 相等)
boolean isAfterBirthday = today.isAfter(birthday);
boolean isEqualToday = LocalDate.of(2025, 11, 06).isEqual(today);
System.out.println("今天在生日之后:" + isAfterBirthday); // 输出:true
System.out.println("指定日期等于今天:" + isEqualToday); // 输出:true
}
}
十七、Java 基础语法总结
Java 基础语法是编写可靠、高效代码的基石,核心可归纳为以下几部分:
-
程序结构:以类为单位,main方法为入口,包和导入语句组织代码;
-
数据类型:8 种基本类型 + 引用类型(类、数组、集合),强类型语言需严格匹配类型;
-
流程控制:分支(if-else、switch)、循环(for、while、do-while)、控制语句(break、continue);
-
面向对象:封装(private+getter/setter)、继承(extends、super)、多态(方法重写 + 父类引用);
-
常用工具:集合(ArrayList动态存储)、泛型(类型安全)、API(String、IO、日期时间);
-
异常处理:try-catch-finally捕获异常,避免程序崩溃。
掌握这些基础后,可进一步学习 Java 进阶内容(如多线程、集合框架深入、Spring 生态等),逐步提升开发能力。

7081

被折叠的 条评论
为什么被折叠?



