1.控制台输入输出:最基本的对话方式
1.1 System.out:程序的"嘴巴"
Java
复制代码
public class ConsoleOutput {
public static void main(String[] args) {
System.out.println("=== 控制台输出 ===");
// 1. System.out.println() - 输出后换行
System.out.println("大家好!"); // 输出后自动换行
System.out.println("我是Java程序。");
// 2. System.out.print() - 输出后不换行
System.out.print("今天是");
System.out.print("美好的一天!"); // 这两行会连在一起
System.out.println(); // 手动换行
// 3. System.out.printf() - 格式化输出(最强大!)
String name = "张三";
int age = 20;
double score = 95.5;
System.out.printf("姓名: %s, 年龄: %d, 成绩: %.2f\n", name, age, score);
// 更多格式化示例
System.out.printf("圆周率: %.3f\n", 3.1415926); // 保留3位小数
System.out.printf("百分比: %.1f%%\n", 85.5); // 显示百分号
System.out.printf("学号: %05d\n", 123); // 5位数字,不足补0
System.out.printf("价格: %,.2f元\n", 1234567.89); // 千位分隔符
// 4. 输出特殊字符
System.out.println("特殊字符:");
System.out.println("换行:第一行\n第二行"); // \n 换行
System.out.println("制表符:A\tB\tC"); // \t 制表符
System.out.println("反斜杠:\\"); // \\ 反斜杠
System.out.println("双引号:\"你好\""); // \" 双引号
System.out.println("单引号:\'Java\'"); // \' 单引号
// 5. 输出各种数据类型
System.out.println("\n各种数据类型输出:");
System.out.println("布尔值:" + true);
System.out.println("整数:" + 100);
System.out.println("小数:" + 3.14);
System.out.println("字符:" + 'A');
System.out.println("字符串:" + "Hello");
// 6. 组合输出
System.out.println("\n=== 学生信息卡 ===");
System.out.println("姓名:李四");
System.out.println("年龄:22岁");
System.out.println("专业:计算机科学");
System.out.println("成绩:A+");
System.out.println("===================");
}
}
1.2 Scanner:程序的"耳朵"
Java
复制代码
import java.util.Scanner;
public class ConsoleInput {
public static void main(String[] args) {
System.out.println("=== 控制台输入 ===");
// 创建Scanner对象(System.in表示从键盘输入)
Scanner scanner = new Scanner(System.in);
// 1. 读取字符串
System.out.print("请输入你的名字: ");
String name = scanner.nextLine(); // 读取整行
System.out.println("你好," + name + "!");
// 2. 读取整数
System.out.print("请输入你的年龄: ");
int age = scanner.nextInt(); // 读取整数
System.out.println("你今年" + age + "岁");
// 3. 读取小数
System.out.print("请输入你的身高(米): ");
double height = scanner.nextDouble(); // 读取小数
System.out.println("你的身高是" + height + "米");
// 4. 读取单词(空格分隔)
System.out.print("请输入三个你喜欢的颜色(用空格分开): ");
String color1 = scanner.next(); // 读取第一个单词
String color2 = scanner.next(); // 读取第二个单词
String color3 = scanner.next(); // 读取第三个单词
System.out.println("你喜欢的颜色是: " + color1 + ", " + color2 + ", " + color3);
// 注意:nextInt/nextDouble后如果要读取字符串,需要先消耗换行符
scanner.nextLine(); // 消耗掉nextDouble留下的换行符
// 5. 读取布尔值
System.out.print("你喜欢Java吗?(true/false): ");
boolean likeJava = scanner.nextBoolean();
if (likeJava) {
System.out.println("太好了!让我们一起学好Java!");
} else {
System.out.println("Java其实很有趣,再试试看!");
}
// 6. 读取单个字符
System.out.print("请输入一个字符: ");
char ch = scanner.next().charAt(0); // 读取第一个字符
System.out.println("你输入的字符是: '" + ch + "'");
// 关闭Scanner(好习惯)
scanner.close();
}
}
1.3 综合示例:用户注册系统
Java
复制代码
import java.util.Scanner;
public class UserRegistration {
public static void main(String[] args) {
System.out.println("=== 用户注册系统 ===");
Scanner scanner = new Scanner(System.in);
// 收集用户信息
System.out.print("请输入用户名: ");
String username = scanner.nextLine();
System.out.print("请输入密码: ");
String password = scanner.nextLine();
System.out.print("请输入年龄: ");
int age = scanner.nextInt();
scanner.nextLine(); // 消耗换行符
System.out.print("请输入邮箱: ");
String email = scanner.nextLine();
System.out.print("请输入手机号: ");
String phone = scanner.nextLine();
// 显示注册信息
System.out.println("\n=== 注册信息确认 ===");
System.out.printf("%-10s: %s\n", "用户名", username);
System.out.printf("%-10s: %s\n", "密码", "******"); // 隐藏密码
System.out.printf("%-10s: %d\n", "年龄", age);
System.out.printf("%-10s: %s\n", "邮箱", email);
System.out.printf("%-10s: %s\n", "手机号", phone);
// 验证确认
System.out.print("\n确认注册吗?(y/n): ");
String confirm = scanner.next();
if (confirm.equalsIgnoreCase("y")) {
System.out.println("注册成功!欢迎," + username + "!");
} else {
System.out.println("注册已取消。");
}
scanner.close();
}
}
2.文件操作:让程序有"记忆力"
2.1 写入文件:保存数据
Java
复制代码
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class WriteToFile {
public static void main(String[] args) {
System.out.println("=== 写入文件 ===");
try {
// 1. 使用FileWriter写入文件(会覆盖原有内容)
FileWriter writer = new FileWriter("student.txt");
writer.write("=== 学生信息 ===\n");
writer.write("姓名: 张三\n");
writer.write("年龄: 20\n");
writer.write("成绩: 95.5\n");
writer.close(); // 一定要关闭文件!
System.out.println("文件写入成功!");
// 2. 追加内容到文件(不覆盖原有内容)
FileWriter appendWriter = new FileWriter("student.txt", true); // true表示追加模式
appendWriter.write("-----------------\n");
appendWriter.write("姓名: 李四\n");
appendWriter.write("年龄: 22\n");
appendWriter.write("成绩: 88.0\n");
appendWriter.close();
System.out.println("追加内容成功!");
// 3. 使用PrintWriter(更方便的写入方式)
PrintWriter printWriter = new PrintWriter("course.txt");
printWriter.println("=== 课程列表 ===");
printWriter.printf("%-15s %-10s %-10s\n", "课程名", "学分", "课时");
printWriter.printf("%-15s %-10d %-10d\n", "Java编程", 3, 48);
printWriter.printf("%-15s %-10d %-10d\n", "数据结构", 4, 64);
printWriter.printf("%-15s %-10d %-10d\n", "数据库原理", 3, 48);
printWriter.close();
System.out.println("课程文件写入成功!");
} catch (IOException e) {
System.out.println("写入文件时出错: " + e.getMessage());
}
}
}
2.2 读取文件:读取数据
Java
复制代码
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class ReadFromFile {
public static void main(String[] args) {
System.out.println("=== 读取文件 ===");
// 方法1:使用BufferedReader(适合读取文本文件)
System.out.println("\n方法1:使用BufferedReader");
try {
BufferedReader reader = new BufferedReader(new FileReader("student.txt"));
String line;
System.out.println("文件内容:");
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (IOException e) {
System.out.println("读取文件时出错: " + e.getMessage());
}
// 方法2:使用Scanner(更方便,功能更强大)
System.out.println("\n方法2:使用Scanner");
try {
Scanner fileScanner = new Scanner(new java.io.File("student.txt"));
System.out.println("逐行读取:");
int lineNumber = 1;
while (fileScanner.hasNextLine()) {
String line = fileScanner.nextLine();
System.out.println("第" + lineNumber + "行: " + line);
lineNumber++;
}
fileScanner.close();
} catch (IOException e) {
System.out.println("读取文件时出错: " + e.getMessage());
}
// 方法3:读取特定格式的数据
System.out.println("\n方法3:读取结构化数据");
try {
Scanner dataScanner = new Scanner(new java.io.File("course.txt"));
// 跳过标题行
if (dataScanner.hasNextLine()) {
dataScanner.nextLine(); // 跳过"=== 课程列表 ==="
dataScanner.nextLine(); // 跳过表头
}
System.out.println("课程信息:");
while (dataScanner.hasNextLine()) {
String courseName = dataScanner.next();
int credit = dataScanner.nextInt();
int hours = dataScanner.nextInt();
System.out.printf("课程: %s, 学分: %d, 课时: %d\n",
courseName, credit, hours);
}
dataScanner.close();
} catch (IOException e) {
System.out.println("读取文件时出错: " + e.getMessage());
}
}
}
2.3 综合示例:学生成绩管理系统
Java
复制代码
import java.io.*;
import java.util.*;
public class StudentGradeManager {
private static final String FILE_NAME = "students.dat";
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("=== 学生成绩管理系统 ===");
boolean running = true;
while (running) {
System.out.println("\n请选择操作:");
System.out.println("1. 添加学生");
System.out.println("2. 查看所有学生");
System.out.println("3. 查找学生");
System.out.println("4. 保存到文件");
System.out.println("5. 从文件加载");
System.out.println("6. 退出");
System.out.print("请输入选择 (1-6): ");
int choice = scanner.nextInt();
scanner.nextLine(); // 消耗换行符
switch (choice) {
case 1:
addStudent();
break;
case 2:
viewAllStudents();
break;
case 3:
findStudent();
break;
case 4:
saveToFile();
break;
case 5:
loadFromFile();
break;
case 6:
running = false;
System.out.println("谢谢使用!再见!");
break;
default:
System.out.println("无效选择,请重新输入!");
}
}
scanner.close();
}
// 存储学生列表
private static List<Student> students = new ArrayList<>();
// 添加学生
private static void addStudent() {
System.out.println("\n=== 添加学生 ===");
System.out.print("请输入学号: ");
String id = scanner.nextLine();
System.out.print("请输入姓名: ");
String name = scanner.nextLine();
System.out.print("请输入年龄: ");
int age = scanner.nextInt();
System.out.print("请输入Java成绩: ");
double javaScore = scanner.nextDouble();
System.out.print("请输入数学成绩: ");
double mathScore = scanner.nextDouble();
scanner.nextLine(); // 消耗换行符
Student student = new Student(id, name, age, javaScore, mathScore);
students.add(student);
System.out.println("学生添加成功!");
}
// 查看所有学生
private static void viewAllStudents() {
System.out.println("\n=== 所有学生信息 ===");
if (students.isEmpty()) {
System.out.println("暂无学生信息!");
return;
}
System.out.printf("%-10s %-10s %-5s %-10s %-10s %-10s\n",
"学号", "姓名", "年龄", "Java成绩", "数学成绩", "平均分");
System.out.println("-".repeat(65));
for (Student student : students) {
System.out.printf("%-10s %-10s %-5d %-10.2f %-10.2f %-10.2f\n",
student.getId(),
student.getName(),
student.getAge(),
student.getJavaScore(),
student.getMathScore(),
student.getAverage());
}
}
// 查找学生
private static void findStudent() {
System.out.print("\n请输入要查找的学生学号: ");
String searchId = scanner.nextLine();
boolean found = false;
for (Student student : students) {
if (student.getId().equals(searchId)) {
System.out.println("找到学生:");
System.out.println(student);
found = true;
break;
}
}
if (!found) {
System.out.println("未找到学号为 " + searchId + " 的学生!");
}
}
// 保存到文件
private static void saveToFile() {
try (PrintWriter writer = new PrintWriter(new FileWriter(FILE_NAME))) {
// 写入学生数量
writer.println(students.size());
// 写入每个学生的信息
for (Student student : students) {
writer.println(student.getId());
writer.println(student.getName());
writer.println(student.getAge());
writer.println(student.getJavaScore());
writer.println(student.getMathScore());
}
System.out.println("数据已保存到文件: " + FILE_NAME);
} catch (IOException e) {
System.out.println("保存文件时出错: " + e.getMessage());
}
}
// 从文件加载
private static void loadFromFile() {
try (Scanner fileScanner = new Scanner(new File(FILE_NAME))) {
// 清空当前学生列表
students.clear();
// 读取学生数量
int count = Integer.parseInt(fileScanner.nextLine());
// 读取每个学生的信息
for (int i = 0; i < count; i++) {
String id = fileScanner.nextLine();
String name = fileScanner.nextLine();
int age = Integer.parseInt(fileScanner.nextLine());
double javaScore = Double.parseDouble(fileScanner.nextLine());
double mathScore = Double.parseDouble(fileScanner.nextLine());
students.add(new Student(id, name, age, javaScore, mathScore));
}
System.out.println("从文件加载了 " + count + " 个学生信息!");
} catch (FileNotFoundException e) {
System.out.println("文件不存在,请先保存数据!");
} catch (IOException e) {
System.out.println("读取文件时出错: " + e.getMessage());
}
}
}
// 学生类
class Student {
private String id;
private String name;
private int age;
private double javaScore;
private double mathScore;
public Student(String id, String name, int age, double javaScore, double mathScore) {
this.id = id;
this.name = name;
this.age = age;
this.javaScore = javaScore;
this.mathScore = mathScore;
}
public double getAverage() {
return (javaScore + mathScore) / 2;
}
// Getter方法
public String getId() { return id; }
public String getName() { return name; }
public int getAge() { return age; }
public double getJavaScore() { return javaScore; }
public double getMathScore() { return mathScore; }
@Override
public String toString() {
return String.format("学号: %s, 姓名: %s, 年龄: %d\n" +
"Java成绩: %.2f, 数学成绩: %.2f, 平均分: %.2f",
id, name, age, javaScore, mathScore, getAverage());
}
}
3.异常处理:I/O操作中的"安全网"
Java
复制代码
import java.io.*;
import java.util.Scanner;
public class IOExceptionHandling {
public static void main(String[] args) {
System.out.println("=== I/O异常处理 ===");
// 1. 文件不存在的异常处理
System.out.println("\n1. 尝试读取不存在的文件:");
try {
Scanner fileScanner = new Scanner(new File("不存在.txt"));
System.out.println("文件内容:" + fileScanner.nextLine());
fileScanner.close();
} catch (FileNotFoundException e) {
System.out.println("错误:文件不存在!");
System.out.println("建议:检查文件路径是否正确");
}
// 2. 写入文件时的异常处理
System.out.println("\n2. 写入文件时的异常:");
try {
FileWriter writer = new FileWriter("/只读目录/test.txt");
writer.write("测试内容");
writer.close();
} catch (IOException e) {
System.out.println("错误:写入文件失败!");
System.out.println("原因:" + e.getMessage());
System.out.println("建议:检查是否有写入权限");
}
// 3. 读取文件时的格式错误
System.out.println("\n3. 读取格式错误的文件:");
try {
Scanner scanner = new Scanner(new File("格式错误.txt"));
int number = scanner.nextInt(); // 如果文件内容不是数字会出错
System.out.println("读取的数字:" + number);
scanner.close();
} catch (FileNotFoundException e) {
System.out.println("错误:文件不存在");
} catch (java.util.InputMismatchException e) {
System.out.println("错误:文件内容格式不正确!");
System.out.println("建议:检查文件内容是否为数字");
}
// 4. 使用try-with-resources自动关闭资源(推荐!)
System.out.println("\n4. 使用try-with-resources:");
// try-with-resources会自动关闭资源,无需手动close
try (FileWriter writer = new FileWriter("test.txt")) {
writer.write("自动关闭资源示例");
System.out.println("文件写入成功!");
} catch (IOException e) {
System.out.println("写入失败:" + e.getMessage());
}
// 这里不需要writer.close(),因为try-with-resources会自动调用
// 5. 综合示例:安全的文件复制
System.out.println("\n5. 安全的文件复制:");
String sourceFile = "student.txt";
String destFile = "student_backup.txt";
try (BufferedReader reader = new BufferedReader(new FileReader(sourceFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(destFile))) {
String line;
int lineCount = 0;
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine(); // 写入换行符
lineCount++;
}
System.out.println("文件复制成功!共复制 " + lineCount + " 行");
} catch (FileNotFoundException e) {
System.out.println("错误:源文件不存在");
} catch (IOException e) {
System.out.println("错误:复制文件时出错 - " + e.getMessage());
}
}
}
4.实用技巧和小知识
4.1 读取大文件
Java
复制代码
import java.io.*;
public class LargeFileReading {
public static void main(String[] args) {
System.out.println("=== 读取大文件 ===");
// 方法1:使用BufferedReader(内存效率高)
try (BufferedReader reader = new BufferedReader(new FileReader("large_file.txt"))) {
String line;
int lineCount = 0;
long startTime = System.currentTimeMillis();
while ((line = reader.readLine()) != null) {
lineCount++;
// 处理每一行(这里只是计数)
if (lineCount % 10000 == 0) {
System.out.println("已读取 " + lineCount + " 行...");
}
}
long endTime = System.currentTimeMillis();
System.out.println("读取完成!共 " + lineCount + " 行");
System.out.println("耗时: " + (endTime - startTime) + " 毫秒");
} catch (IOException e) {
System.out.println("读取文件时出错: " + e.getMessage());
}
// 方法2:读取二进制文件
System.out.println("\n=== 读取二进制文件 ===");
try (FileInputStream fis = new FileInputStream("binary.dat");
BufferedInputStream bis = new BufferedInputStream(fis)) {
byte[] buffer = new byte[1024]; // 1KB缓冲区
int bytesRead;
int totalBytes = 0;
while ((bytesRead = bis.read(buffer)) != -1) {
totalBytes += bytesRead;
// 处理二进制数据
}
System.out.println("读取了 " + totalBytes + " 字节的二进制数据");
} catch (IOException e) {
System.out.println("读取二进制文件时出错: " + e.getMessage());
}
}
}
4.2 日志记录
java
复制代码
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
public class LoggingExample {
public static void main(String[] args) {
System.out.println("=== 日志记录系统 ===");
// 记录不同级别的日志
log("INFO", "程序启动");
log("DEBUG", "加载配置文件");
log("WARNING", "内存使用率较高");
log("ERROR", "数据库连接失败");
log("INFO", "程序退出");
// 查看日志文件
System.out.println("\n=== 日志文件内容 ===");
try (BufferedReader reader = new BufferedReader(new FileReader("app.log"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("读取日志文件时出错: " + e.getMessage());
}
}
// 日志记录方法
public static void log(String level, String message) {
// 获取当前时间
String timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
// 格式化的日志条目
String logEntry = String.format("[%s] %s: %s", timestamp, level, message);
// 输出到控制台
System.out.println(logEntry);
// 写入日志文件(追加模式)
try (PrintWriter writer = new PrintWriter(new FileWriter("app.log", true))) {
writer.println(logEntry);
} catch (IOException e) {
System.out.println("写入日志文件时出错: " + e.getMessage());
}
}
}
5.常见问题和解决方案
问题1:Scanner输入问题
java
复制代码
import java.util.Scanner;
public class ScannerProblems {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 常见问题1:nextInt后接nextLine
System.out.print("请输入年龄: ");
int age = scanner.nextInt();
scanner.nextLine(); // 解决方案:消耗掉换行符
System.out.print("请输入姓名: ");
String name = scanner.nextLine(); // 现在可以正确读取
System.out.println("年龄: " + age + ", 姓名: " + name);
// 常见问题2:输入类型不匹配
System.out.print("请输入一个数字: ");
if (scanner.hasNextInt()) {
int num = scanner.nextInt();
System.out.println("你输入的是数字: " + num);
} else {
String input = scanner.next();
System.out.println("错误:'" + input + "' 不是有效的数字!");
}
scanner.close();
}
}
问题2:文件路径问题
java
复制代码
import java.io.File;
public class FilePathProblems {
public static void main(String[] args) {
System.out.println("=== 文件路径问题 ===");
// 1. 绝对路径 vs 相对路径
String absolutePath = "C:\\Users\\admin\\file.txt"; // Windows绝对路径
String relativePath = "data/file.txt"; // 相对路径
System.out.println("绝对路径: " + absolutePath);
System.out.println("相对路径: " + relativePath);
// 2. 检查文件是否存在
File file = new File(relativePath);
if (file.exists()) {
System.out.println("文件存在!");
System.out.println("文件大小: " + file.length() + " 字节");
System.out.println("可读: " + file.canRead());
System.out.println("可写: " + file.canWrite());
} else {
System.out.println("文件不存在!");
}
// 3. 创建目录
File directory = new File("logs");
if (!directory.exists()) {
if (directory.mkdir()) {
System.out.println("目录创建成功: " + directory.getAbsolutePath());
} else {
System.out.println("目录创建失败!");
}
}
// 4. 列出目录内容
File currentDir = new File(".");
System.out.println("\n当前目录内容:");
String[] files = currentDir.list();
if (files != null) {
for (String f : files) {
System.out.println(f);
}
}
}
}
总结:最重要的三点
- Scanner和System.out是基础 :
System.out 用于输出,System.in 用于输入
Scanner 让输入变得简单,记得正确处理换行符
- 文件操作三步曲 :
- 创建File对象指定文件
- 使用Reader/Writer进行读写
- 记得关闭资源(用try-with-resources)
- 异常处理是必须的 :
- I/O操作容易出错,必须处理异常
- 使用try-catch保护代码
- 给用户友好的错误提示