Java 输入输出(I/O)详解与常用代码大全
Java 的输入输出(I/O)主要通过java.io和java.nio包实现,用于读取文件、键盘输入、网络数据等,以及写入文件、控制台输出等。下面按场景分类,汇总最实用、最常用的代码示例(基于 Java 8+,推荐使用 try-with-resources 自动关闭资源)。
1. 控制台输入(键盘输入)
最常用:Scanner(推荐新手)
importjava.util.Scanner;Scannersc=newScanner(System.in);// 读取一行字符串System.out.print("请输入姓名:");Stringname=sc.nextLine();// 读取整数System.out.print("请输入年龄:");intage=sc.nextInt();// 读取浮点数doublescore=sc.nextDouble();// 关闭(可选,System.in 不建议关闭)sc.close();高级:BufferedReader(性能更好,读取大输入)
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.io.IOException;BufferedReaderbr=newBufferedReader(newInputStreamReader(System.in));System.out.print("请输入内容:");Stringline=br.readLine();// 读取一行2. 控制台输出
System.out.println("普通输出,自动换行");System.out.print("不换行输出");System.out.printf("格式化输出:年龄 %d,成绩 %.2f\n",age,score);3. 文件读取(最常用方式)
方式一:Files + Paths(Java 7+,最简洁)
importjava.nio.file.Files;importjava.nio.file.Paths;importjava.io.IOException;importjava.util.List;try{// 读取整个文件为字符串Stringcontent=Files.readString(Paths.get("file.txt"));// 读取所有行到 ListList<String>lines=Files.readAllLines(Paths.get("file.txt"));// 逐行读取(推荐大文件)Files.lines(Paths.get("file.txt")).forEach(System.out::println);}catch(IOExceptione){e.printStackTrace();}方式二:BufferedReader(经典,高效)
importjava.io.*;try(BufferedReaderbr=newBufferedReader(newFileReader("file.txt"))){Stringline;while((line=br.readLine())!=null){System.out.println(line);}}catch(IOExceptione){e.printStackTrace();}4. 文件写入
方式一:Files(最简洁)
importjava.nio.file.*;try{// 写入字符串(覆盖)Files.writeString(Paths.get("output.txt"),"Hello Java");// 追加写入多行Files.write(Paths.get("output.txt"),List.of("第一行","第二行"),StandardOpenOption.APPEND,StandardOpenOption.CREATE);}catch(IOExceptione){e.printStackTrace();}方式二:BufferedWriter(经典)
try(BufferedWriterbw=newBufferedWriter(newFileWriter("output.txt",true))){// true 为追加bw.write("这是写入的内容");bw.newLine();// 换行bw.write("第二行");}catch(IOExceptione){e.printStackTrace();}5. 复制文件(实用工具方法)
try{Files.copy(Paths.get("source.txt"),Paths.get("target.txt"),StandardCopyOption.REPLACE_EXISTING);}catch(IOExceptione){e.printStackTrace();}6. 序列化对象(保存对象到文件)
// 对象需实现 Serializable 接口classPersonimplementsjava.io.Serializable{Stringname;intage;// transient 字段不序列化(如密码)transientStringpassword;}// 序列化(保存对象)try(ObjectOutputStreamoos=newObjectOutputStream(newFileOutputStream("person.obj"))){oos.writeObject(newPerson("张三",25));}// 反序列化(读取对象)try(ObjectInputStreamois=newObjectInputStream(newFileInputStream("person.obj"))){Personp=(Person)ois.readObject();System.out.println(p.name);}7. 常用路径操作(java.nio.file)
Pathpath=Paths.get("dir/sub/file.txt");// 获取文件名、父目录、扩展名StringfileName=path.getFileName().toString();// file.txtStringparent=path.getParent().toString();// dir/subStringext=fileName.substring(fileName.lastIndexOf(".")+1);// txt// 创建目录Files.createDirectories(Paths.get("new/dir"));// 判断文件是否存在if(Files.exists(path)){...}// 删除文件/目录Files.deleteIfExists(path);总结对比表(推荐选择)
| 场景 | 推荐方式 | 原因 |
|---|---|---|
| 简单控制台输入 | Scanner | 易用、支持多种类型 |
| 大量文本读取 | BufferedReader / Files.lines | 高效、内存友好 |
| 小文件读写 | Files.readString/writeString | 代码最少 |
| 大文件读写 | BufferedReader/Writer | 性能好 |
| 复制/移动/删除文件 | Files.copy/move/delete | 简洁原子操作 |
| 保存对象状态 | ObjectOutputStream | 序列化 |
注意事项
- 始终使用try-with-resources自动关闭资源,避免资源泄露。
- 处理IOException(文件不存在、权限问题等)。
- 路径使用
Paths.get(),跨平台兼容(Windows/Linux)。 - 大文件避免一次性读入内存。
这些代码覆盖了 Java I/O 的 95% 日常需求,直接复制即可使用。如果需要网络 I/O(如 Socket)、JSON 文件读写、CSV 处理等高级用法,欢迎继续提问!