Java Stream、File 与 IO

读写文件是几乎所有程序都要做的事。Java 用 File 描述路径与文件本身,用各种“流”搬运字节或字符数据(这里的 Stream 指 java.io 的输入输出流,与集合的 Stream API 无关)。本节所有流都配合 try-with-resources 使用,自动关闭、不泄漏资源。

File 类:路径与文件操作

File 既能代表文件也能代表目录:createNewFile 创建文件、isFile / isDirectory 判断类型、delete 删除、getName / getPath 看路径;列目录用 String[] names = dir.list() 或 dir.listFiles()。

import java.io.File;

public class FileDemo {
    public static void main(String[] args) throws Exception {
        File f = new File("hello.txt");  // 路径对象,可相对可绝对
        f.createNewFile();               // 创建文件
        System.out.println(f.exists());  // 输出:true
        System.out.println(f.isFile());  // 输出:true
        f.delete();                      // 删除文件
        System.out.println(f.exists());  // 输出:false
    }
}

字节流:InputStream 与 OutputStream

字节流按字节处理,可读写文本、图片等一切文件。FileInputStream / FileOutputStream 读写文件(注意 try(资源){...} 就是 try-with-resources:括号里声明的流在代码块结束时自动调用 close(),正常返回或抛异常都一样,无需手写 finally):

import java.io.FileInputStream;
import java.io.FileOutputStream;

public class ByteStreamDemo {
    public static void main(String[] args) throws Exception {
        try (FileOutputStream out = new FileOutputStream("data.txt")) {
            out.write("Hello IO".getBytes());   // 写字节
        }
        try (FileInputStream in = new FileInputStream("data.txt")) {
            byte[] buf = new byte[1024];
            int len = in.read(buf);             // 返回实际读到的字节数
            System.out.println(new String(buf, 0, len)); // 输出:Hello IO
        }
    }
}

字符流与缓冲读取:Reader、Writer、BufferedReader

字符流按字符读写,适合处理文本。FileWriter 写入、FileReader 读入,建议显式指定 UTF-8 字符集防乱码;逐行读文本推荐 BufferedReader.readLine():

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.nio.charset.StandardCharsets;

public class CharStreamDemo {
    public static void main(String[] args) throws Exception {
        try (FileWriter w = new FileWriter("note.txt", StandardCharsets.UTF_8)) {
            w.write("第一行\n第二行");
        }
        try (BufferedReader br = new BufferedReader(
                new FileReader("note.txt", StandardCharsets.UTF_8))) {
            String line;
            while ((line = br.readLine()) != null) {  // 逐行读
                System.out.println(line);             // 输出:第一行、第二行
            }
        }
    }
}

Scanner 读控制台与文件

Scanner 既能读键盘输入(System.in)也能读文件,按行或空白切分都很方便:

import java.io.File;
import java.util.Scanner;

public class ScanDemo {
    public static void main(String[] args) throws Exception {
        try (Scanner sc = new Scanner(System.in)) {   // 读控制台
            System.out.print("请输入姓名:");
            System.out.println("你好," + sc.nextLine());
        }
        try (Scanner fs = new Scanner(new File("note.txt"))) {  // 读文件
            while (fs.hasNextLine()) {
                System.out.println(fs.nextLine());    // 输出:文件每一行
            }
        }
    }
}

小结:File 管路径与文件,字节流处理二进制、字符流处理文本,逐行读优先 BufferedReader,交互输入用 Scanner;所有流都要放进 try-with-resources 自动关闭,并显式指定 UTF-8 避免乱码。

笔记加载中…