1.控制台输入输出:最基本的对话方式
1.1 System.out:程序的"嘴巴"
public class ConsoleOutput {
public static void main(String[] args) {
System.out.println("=== 控制台输出 ===");
System.out.println("大家好!");
System.out.println("我是Java程序。");
System.out.print("今天是");
System.out.print("美好的一天!");
System.out.println();
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);
System.out.printf("百分比: %.1f%%\n", 85.5);
System.out.printf("学号: %05d\n", 123);
System.out.printf("价格: %,.2f元\n", 1234567.89);
System.out.println("特殊字符:");
System.out.println("换行:第一行\n第二行");
System.out.println("制表符:A\tB\tC");
System.out.println("反斜杠:\\");
System.out.println("双引号:\"你好\"");
System.out.println("单引号:\'Java\'");
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");
System.out.println("\n=== 学生信息卡 ===");
System.out.println("姓名:李四");
System.out.println("年龄:22岁");
System.out.println("专业:计算机科学");
System.out.println("成绩:A+");
System.out.println("===================");
}
}
1.2 Scanner:程序的"耳朵"
import java.util.Scanner;
public class ConsoleInput {
public static void main(String[] args) {
System.out.println("=== 控制台输入 ===");
Scanner scanner = new Scanner(System.in);
System.out.print("请输入你的名字: ");
String name = scanner.nextLine();
System.out.println("你好," + name + "!");
System.out.print("请输入你的年龄: ");
int age = scanner.nextInt();
System.out.println("你今年" + age + "岁");
System.out.print("请输入你的身高(米): ");
double height = scanner.nextDouble();
System.out.println("你的身高是" + height + "米");
System.out.print("请输入三个你喜欢的颜色(用空格分开): ");
String color1 = scanner.next();
String color2 = scanner.next();
String color3 = scanner.next();
System.out.println("你喜欢的颜色是: " + color1 + ", " + color2 + ", " + color3);
scanner.nextLine();
System.out.print("你喜欢Java吗?(true/false): ");
boolean likeJava = scanner.nextBoolean();
if (likeJava) {
System.out.println("太好了!让我们一起学好Java!");
} else {
System.out.println("Java其实很有趣,再试试看!");
}
System.out.print("请输入一个字符: ");
char ch = scanner.next().charAt(0);
System.out.println("你输入的字符是: '" + ch + "'");
scanner.close();
}
}
1.3 综合示例:用户注册系统
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 写入文件:保存数据
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 {
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("文件写入成功!");
FileWriter appendWriter = new FileWriter("student.txt", true);
appendWriter.write("-----------------\n");
appendWriter.write("姓名: 李四\n");
appendWriter.write("年龄: 22\n");
appendWriter.write("成绩: 88.0\n");
appendWriter.close();
System.out.println("追加内容成功!");
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 读取文件:读取数据
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("=== 读取文件 ===");
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());
}
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());
}
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 综合示例:学生成绩管理系统
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;
}
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操作中的"安全网"
import java.io.*;
import java.util.Scanner;
public class IOExceptionHandling {
public static void main(String[] args) {
System.out.println("=== I/O异常处理 ===");
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("建议:检查文件路径是否正确");
}
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("建议:检查是否有写入权限");
}
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("建议:检查文件内容是否为数字");
}
System.out.println("\n4. 使用try-with-resources:");
try (FileWriter writer = new FileWriter("test.txt")) {
writer.write("自动关闭资源示例");
System.out.println("文件写入成功!");
} catch (IOException e) {
System.out.println("写入失败:" + e.getMessage());
}
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 读取大文件
import java.io.*;
public class LargeFileReading {
public static void main(String[] args) {
System.out.println("=== 读取大文件 ===");
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());
}
System.out.println("\n=== 读取二进制文件 ===");
try (FileInputStream fis = new FileInputStream("binary.dat");
BufferedInputStream bis = new BufferedInputStream(fis)) {
byte[] buffer = new byte[1024];
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 日志记录
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输入问题
import java.util.Scanner;
public class ScannerProblems {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入年龄: ");
int age = scanner.nextInt();
scanner.nextLine();
System.out.print("请输入姓名: ");
String name = scanner.nextLine();
System.out.println("年龄: " + age + ", 姓名: " + name);
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:文件路径问题
import java.io.File;
public class FilePathProblems {
public static void main(String[] args) {
System.out.println("=== 文件路径问题 ===");
String absolutePath = "C:\\Users\\admin\\file.txt";
String relativePath = "data/file.txt";
System.out.println("绝对路径: " + absolutePath);
System.out.println("相对路径: " + relativePath);
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("文件不存在!");
}
File directory = new File("logs");
if (!directory.exists()) {
if (directory.mkdir()) {
System.out.println("目录创建成功: " + directory.getAbsolutePath());
} else {
System.out.println("目录创建失败!");
}
}
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保护代码
- 给用户友好的错误提示