一、知识考察:
I/O口操作主要是指使用Java程序完成输入(Input)、输出(Output)操作。输入是指将文件内容以数据流的形式读入内存,输出的是通过Java程序将内存中的数据写入文件。
1.File类
(1)创建File类对象(3种方法)
File(String pathname) //通过指定的一个字符类型的文件路径创建File对象
File file1 = new File("C:\\Users\\Username\\Documents\\example.txt");
//绝对路径
File(String parent,String child) //根据指定的一个字符串类型的父路径和一个字符串类型的子路径(包含文件名称)创建一个File对象
File file2 = new File("C:\\Users\\Username\\Documents", "example.txt");
File(File parent,String child) //根据指定的一个File类的父路径和一个字符串类型的子路径(包含文件名称)创建一个File对象
// 创建父路径的File对象
File parentDir = new File("C:\\Users\\Username\\Documents");
// 使用父路径和子路径创建File对象
File childFile = new File(parentDir, "example.txt");
(2)File类的常用方法
boolean exists() //若文件存在返回true,否则返回false
boolean delete() //删除Flie对象对应的文件或目录,删除成功返回true,否则false
boolean createNewFile() //当File对象对应的文件不存在时,创建一个文件,成功创建返回true,否则false
String getName()
String getPath()
long length() //返回文件内容的长度(单位字节)
2.字节流
计算机中无论是文本、图片、音频还是视频,所有文件都是以二进制(字节)形式存在的。对于字节的输入输出,I/O系统提供了一系列流,统称字节流。根据传输方向可分为字节输入流和字节输出流。InputStream和OutputStream是字节流的顶级父类,所有的字节输入流都继承InputStream,所有的字节输出流都继承OutputStream。
(1)InputStream的常用方法
int read() //从输入流读取一字节(8位),把它转换为0-255的整数,并返回这一整数
int read(byte[ ] b) //从输入流读取若干字节,把它们保存到参数b指定的字节数组中,返回的整数表示读取的字节数
int read(byte[ ] b,int off,int len) //off表示指定字节数组保存数据的起始索引,len表示读取的字节数
void close()
(2)OutputStream的常用方法
void write(int b)
void write(byte[ ] b)
void write(byte[ ] b,int off ,int len)
void flush() //刷新输出流并强制写出所有缓冲的输出字节
void close()
(3)FileInputStream和FileOutputStream
它们分别是InputStream和OutputStream的子类
3.字符流
略
二、实验题目
1.模拟实现网络平台账号注册:要求输入的密码长度为8,且包含数字、大写字母和小写字母三种字符,将输入的用户名和密码写入文件test.txt,并读取test.txt内容显示到控制台上。输出形式为用户名:密码。
2.利用字节流FileInputStream和FileOutputStream 将文件a.txt 和 b.txt进行合并。
提示:首先对文件a.txt和b.txt建立文件输入流FileInputStream的对象 fin1和fin2,在对c.txt建立文件输出流FileOutputStream的对象fout,并利用循环,分别从a.txt和b.txt 逐个字节读出复制到c.txt中。
3.编写一个程序,分别使用字节流和字符流拷贝一个文本文件。提示:使用字节流进行拷贝的时候可以定义一个指定长度的数组作为缓冲区,使用字符流拷贝的时候可以使用BufferedReader和BufferedWriter。
4.某人在玩游戏的时候输入密码123456后成功进入游戏(输错5次则被强行退出),要求用程序实现密码验证的过程。
提示:(1)使用System.in包装为字符流读取键盘输入;(2)使用BufferedReader对字符流进行包装,调用readLine()方法每次读取一;(3)密码错误超出5次,可以使用System.exit(0)结束程序。
三、解题代码:
第一题
import java.io.*;
import java.util.Scanner;
//第1
public class RegistrationSimulator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入用户名:");
String username = scanner.nextLine();
System.out.println("请输入密码:");
String password = scanner.nextLine();
//如果密码格式正确,则写入文件
if (isValidPassword(password)) {
try (//创建字符输入流,读取文件中的字符
FileWriter writer = new FileWriter("D:\\zjl\\test.txt", true)) {//追加
writer.write(username + ":" + password + "\n");
} catch (IOException e) {
e.printStackTrace();
}
try (BufferedReader reader = new BufferedReader(new FileReader("D:\\zjl\\test.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("密码不符合要求,请重新输入!");
}
}
private static boolean isValidPassword(String password) {
if (password.length() != 8) {
return false;
}
boolean hasDigit = false;
boolean hasUpperCase = false;
boolean hasLowerCase = false;
//foreach循环:for(容器中元素类型 存储容器内元素临时变量:容器容量)
for (char c : password.toCharArray()) {
if (Character.isDigit(c)) {
hasDigit = true;
} else if (Character.isUpperCase(c)) {
hasUpperCase = true;
} else if (Character.isLowerCase(c)) {
hasLowerCase = true;
}
}
return hasDigit && hasUpperCase && hasLowerCase;
}
}
第二题
import java.io.*;
public class FileMerger {
public static void main(String[] args){
mergeFiles("D:\\zjl\\a.txt", "D:\\zjl\\b.txt", "D:\\zjl\\c.txt");
}
//文本文件不存在时自动创建
public static void mergeFiles(String file1, String file2, String outputFile) {
try {
//方法1:创建文件字节输出流、文件字节输入流
FileInputStream fis1 = new FileInputStream(file1);
FileInputStream fis2 = new FileInputStream(file2);
FileOutputStream fos = new FileOutputStream(outputFile);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fis1.read(buffer)) != -1) {
//read(字节数组);从输入流fis1中读取若干字节,把他们存入字符数组buffer中,返回一个整数(读取的字节数)
fos.write(buffer, 0, bytesRead);
//write(字节数组,数组起始索引,读取的字节的长度len);将字节数组中从索引0开始的len字节写入输出流fos
}
//同理,可得
while ((bytesRead = fis2.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
//System.out.println(buffer);
} catch (IOException e) {
e.printStackTrace();
}
}
}
第三题
//第3题
import java.io.*;
public class BufferedReaderTest{
public static void main(String[] args)throws Exception{
//方法1
FileReader f1 = new FileReader("D:\\zjl\\src.txt");
BufferedReader br=new BufferedReader(f1);
//方法2
BufferedWriter bw=new BufferedWriter(new FileWriter("D:\\zjl\\sy.txt"));
String str;
while ((str=br.readLine())!=null){
bw.write(str);
bw.newLine();
}
br.close();
bw.close();
}
}
第四题
方法1:
package Experiment12;
//第4
import java.io.*;
public class Password{
public static void main(String[] args) {
String correctPassword = "123456";
int attemptCount = 0;//记录输密码的次数
boolean isAccessGranted = false;
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
// BufferedReader类是Reader的子类
while (attemptCount < 5 && !isAccessGranted) {
System.out.print("请输入密码: ");
try {
String inputPassword = reader.readLine();//读取一行文本并返回
// (String类方法) Boolean equals(Object obj)比较obj与当前字符是否匹配
if (inputPassword.equals(correctPassword)) {
System.out.println("密码正确,进入游戏。");
isAccessGranted = true;
} else {
System.out.println("密码错误,请重试。");
attemptCount++;
}
} catch (IOException e) {
System.out.println("输入错误,请重试。");
}
}
if (!isAccessGranted) {
System.out.println("密码错误超过5次,程序将退出。");
System.exit(0);//参数是一个整数,通常用于标识程序的退出状态
}
}
}
方法2:
package practical;
import java.io.*;
public class Test12_3 {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// InputStreamReader:这个类是一个桥接类,它将字节流转换为字符流。
// System.in 是一个输入流,代表键盘输入,
// 这里的 InputStreamReader 将字节(从键盘输入)转换为字符,以便 BufferedReader 可以处理。
String password = "";
boolean b = false;
for (int i = 0; i < 5; i++) {
System.out.println("请输入密码:");
password = br.readLine();
if (password.equals("123456")) {
System.out.println("恭喜你进入游戏");
b = true;
break;
}
}
if (!b) {
System.out.println("密码错误,游戏结束");
System.exit(0);
}
}
}
说明:复习内容基于本人实际学习情况,发布文章仅用于记录。如有错误,欢迎纠正。
第六部分