以下是一些可以学习Java IO流的编程题:
1. Java IO流实现一个文件复制程序,将一个文件的内容复制到另一个文件中。
import java.io.*;
//Java IO流实现一个文件复制程序,将一个文件的内容复制到另一个文件中。
public class FileCopy {
public static void main(String[] args) {
String sourceFilePath = "D:\\kecheng\\month316\\src\\wenjian\\123.txt";
String targetFilePath = "D:\\kecheng\\month316\\src\\wenjian\\456.txt";
try (InputStream inputStream = new FileInputStream(sourceFilePath);
OutputStream outputStream = new FileOutputStream(targetFilePath)) {
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
System.out.println("文件复制成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 在这个示例中,我们使用了Java的InputStream和OutputStream类来读取和写入文件。
* 我们首先指定了源文件和目标文件的路径,然后使用try-with-resources语句创建了输入流和输出流对象。
* 我们使用一个缓冲区数组来读取和写入文件,并且在循环中不断读取源文件的内容,然后写入到目标文件中。
* 最后,我们关闭输入流和输出流,并输出一个成功的消息。
*/
2. Java IO流实现一个文件夹遍历程序,输出指定文件夹下的所有文件和子文件夹。
package wenjian;
import java.io.File;
//Java IO流实现一个文件夹遍历程序,输出指定文件夹下的所有文件和子文件夹。
public class FolderTraverse {
public static void main(String[] args) {
File folder = new File("D:\\kecheng\\month316\\src");
traverseFolder(folder);
}
public static void traverseFolder(File folder) {
if (folder.isDirectory()) {
System.out.println("Folder: " + folder.getAbsolutePath());
File[] files = folder.listFiles();
if (files != null) {
for (File file : files) {
traverseFolder(file);
}
}
} else {
System.out.println("File: " + folder.getAbsolutePath());
}
}
}
/**
*说明:
* 1. 使用 `java.io.File` 类来表示文件和文件夹。
* 2. `listFiles()` 方法返回文件夹下的所有文件和子文件夹,如果是文件则直接输出,如果是文件夹则递归调用 `traverseFolder()` 方法。
* 3. `isDirectory()` 方法判断是否是文件夹。
* */
3. Java IO流实现一个读取文本文件的程序,将文件内容读取到内存中并输出。
package wenjian;
//Java IO流实现一个写入文本文件的程序,将指定的字符串写入到文件中。
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class TextFileReader {
public static void main(String[] args) {
String filePath = "D:\\kecheng\\month316\\src\\wenjian\\456.txt"; // 指定文件路径
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(filePath));
String line = null;
while ((line = reader.readLine()) != null) { // 逐行读取文件内容
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
/**
* 其中,我们使用了`BufferedReader`类来读取文件内容,`FileReader`类用于创建读取文件的管道。
* 在`try-catch`语句块中,我们使用`readLine()`方法逐行读取文件内容,并将每行内容输出到控制台。
* 最后在`finally`语句块中关闭文件读取管道。
*/
4. Java IO流实现一个写入文本文件的程序,将指定的字符串写入到文件中。
package wenjian;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class control1 {
public static void main(String[] args) throws IOException {
// 1 创建一个文件字节输出流管道与目标文件联通
//第二个参数 表示是否实行追加写
OutputStream os = new FileOutputStream("D:\\kecheng\\month316\\src\\wenjian\\123.txt",true);
//2 写出数据到目标文件
os.write('a');
os.write(99);
//写一个字节数组
byte[] buff = {'w',98,99,100};//写一个字节数组
os.write(buff);
os.write(buff,1,2);//写字节数组的一部分
os.write("山西晋中理工学院".getBytes());
os.flush();//刷新
os.close();//关闭
}
}
5. Java IO流实现一个使用 Scanner 读取文本文件的程序,支持按行读取和按分隔符读取。
package wenjian;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
//5. Java IO流实现一个使用 Scanner 读取文本文件的程序,支持按行读取和按分隔符读取。
public class TextFileReader1 {
public static void main(String[] args) {
String filePath = "D:\\kecheng\\month316\\src\\wenjian\\123.txt"; // 指定文件路径
File file = new File(filePath);
try (Scanner scanner = new Scanner(file)) {
// 按行读取文件内容
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
// 在这里处理每一行的内容
System.out.println(line);
}
// 按分隔符读取文件内容
scanner.useDelimiter(",");
while (scanner.hasNext()) {
String token = scanner.next();
// 在这里处理每一个分隔符分隔的内容
System.out.println(token);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 在上面的代码中,我们使用`Scanner`类的`hasNextLine()`和`nextLine()`方法按行读取文件内容,并在每一行读取之后对其进行处理。
* 我们也可以使用`Scanner`类的`useDelimiter()`方法设置分隔符来按分隔符读取文件内容,并在每一个分隔符分隔的内容读取之后对其进行处理。
* 最后,在`try-with-resources`语句块中,我们使用`Scanner`类的`close()`方法关闭`Scanner`对象。
*/
6. 将一个视频文件复制到其他的目录下
package wenjian;
import java.io.*;
/**
* 需求:将一个视频文件复制到其他的目录下
*
* 思路:
*
* - 创建数据输入流 对象
* - 创建一个输出流对象 指定目的地
* - 进行数据的读写 完成复制
* - 释放资源
*/
public class controlc {
public static void main(String[] args) {
InputStream is = null;
OutputStream os =null;
try {
is = new FileInputStream("C:\\Users\\Lenovo\\Desktop\\产业学院上课用\\001\\01_完成购票系统的评分功能.mp4");
os = new FileOutputStream("D:\\kecheng\\month316\\src\\wenjian\\01_完成购票系统的评分功能.mp4");
//定义一个字节数组 作为缓冲区
byte[] buff = new byte[1024];
int len;//记录每次读取的字节数
while((len = is.read(buff)) != -1){
// 将缓冲区的数据通过输出流 输出到目标文件
os.write(buff,0,len);
}
System.out.println("文件复制完成");
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}finally {
//关闭流 释放资源
try {
if (os !=null){
os.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
if (is !=null){
is.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
7. 拷贝文件夹
package wenjian;
import java.io.*;
/**
* ## 拷贝文件夹
* <p>
* 需求:将某个磁盘的文件夹拷贝到另一个文件夹中,包括文件夹中的全部信息
* <p>
* 分析:IO默认的情况是不可以直接拷贝文件夹的
*/
public class CopyDir {
public static void main(String[] args) {
copy(new File("d:\\workSpace"), new File("d://code"));
}
public static void copy(File src, File dest) {
//1 判断源目录是否存在
if (src != null && src.exists() && src.isDirectory()) {
// 在目标路径下 创建一个源目录的文件夹
File destDir = new File(dest, src.getName());
destDir.mkdirs();//创建处复制目录的顶层目录
// 2 判断原目录下是否包含以及目录
File[] files = src.listFiles();
if (files != null && files.length > 0) {
// 3 开始遍历一级目录
for (File file : files) {
// 4 判断是文件还是文件夹 如果是文件 直接复制
if (file.isFile()) {
copyFile(file, new File(destDir, file.getName()));
} else {
// 5 如果是文件夹 则继续递归复制
copy(file, destDir);
}
}
}
}
}
public static void copyFile(File srcFile, File destFile) {
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(srcFile);
os = new FileOutputStream(destFile);
//定义一个字节数组 作为缓冲区
byte[] buff = new byte[1024];
int len;//记录每次读取的字节数
while ((len = is.read(buff)) != -1) {
// 将缓冲区的数据通过输出流 输出到目标文件
os.write(buff, 0, len);
}
System.out.println("文件复制完成");
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
//关闭流 释放资源
try {
if (os != null) {
os.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
8. 自动登录小程序
- 将正确的用户名和密码手动保存到本地文件 userInfo.txt文件中
保存的格式为:username=zhangsan&password=123456 - 第一次登录让用户键盘输入用户名和密码 比较用户输入的用户名和密码是否和文件中保存的一致
如果一致则打印登录成功,并将用户登录的数据保存到本地的cookie.txt文件中 保存的格式:username = zhangsan
password=123456 - 如果不一致,打印登录失败 不需要保存数据搭配cookie.txt 再次运行时,则从本地cookie.txt文件中读取第一次保存的数据
实现自动登录
包含文件
第一种方式
package wenjian;
import java.io.*;
import java.util.Scanner;
public class AutoLogin {
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
login();
}
public static void login() throws IOException {
File file = new File("D:\\kecheng\\month316\\src\\wenjian\\cookie.txt");
if (file.exists()){
BufferedReader cbr = new BufferedReader(new FileReader(file));
String cname = cbr.readLine() ;
String cpass = cbr.readLine();
if (cname != null && cpass !=null){
System.out.println("登录成功");
cbr.close();
}else{
firstLogin();
}
}else{
firstLogin();
}
}
public static void firstLogin() throws IOException {
System.out.println("请输入用户名:");
String username = scanner.nextLine();
System.out.println("请输入密码:");
String password = scanner.nextLine();
Reader r= new FileReader("D:\\kecheng\\month316\\src\\wenjian\\userInfo.txt");
BufferedReader br = new BufferedReader(r);
String line = br.readLine();
String[] lineStr = line.split("&");
String txtUserName = lineStr[0].split("=")[1];
String txtPassword = lineStr[1].split("=")[1];
System.out.println(txtUserName + "---" + txtPassword);
if(username.equals(txtUserName)&&password.equals(txtPassword)){
//如果一致则打印登录成功,并将用户登录的数据保存到本地的cookie.txt文件中
// * 保存的格式:username = zhangsan
// * password=123456
// * 如果不一致,打印登录失败 不需要保存数据搭配cookie.txt
BufferedWriter bw = new BufferedWriter(new
FileWriter("D:\\kecheng\\month316\\src\\wenjian\\cookie.txt"));
String wUsername = "username=" +username;
String wPassword = "password=" + password;
bw.write(wUsername);
bw.newLine();
bw.write(wPassword);
bw.close();
System.out.println("登录成功");
}
br.close();
}
}
第二种方式
package wenjian;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class LoginProgram {
public static void main(String[] args) throws FileNotFoundException {
System.out.println("欢迎使用登录程序!");
File file1 = new File("D:\\kecheng\\month316\\src\\wenjian\\cookie1.txt");
try {
Scanner scanner = new Scanner(file1);
if (scanner.hasNext()) {
ag();
} else {
af();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Scanner scanner = new Scanner(System.in);
private static void ag() {
File file1 = new File("D:\\kecheng\\month316\\src\\wenjian\\cookie1.txt");
try {
Scanner scanner = new Scanner(file1);
String line = scanner.nextLine();
String[] parts = line.split(",");
String savedUsername = parts[0];
String savedPassword = parts[1];
scanner.close();
String inputUsername = savedUsername;
String inputPassword = savedPassword;
// 比对账户密码
if (checkAccount(inputUsername, inputPassword)) {
System.out.println("登录成功!");
} else {
System.out.println("登录失败,请检查用户名和密码!");
}
}catch (IOException e) {
e.printStackTrace();
}
}
private static void af() {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入您的用户名:");
String username = scanner.nextLine();
System.out.println("请输入您的密码:");
String password = scanner.nextLine();
// 将账户密码保存到文件中
saveAccount(username, password);
// 模拟登录流程
System.out.println("请重新输入您的用户名:");
String inputUsername = scanner.nextLine();
System.out.println("请重新输入您的密码:");
String inputPassword = scanner.nextLine();
// 比对账户密码
if (checkAccount(inputUsername, inputPassword)) {
File file1 = new File("D:\\kecheng\\month316\\src\\wenjian\\cookie1.txt");
try {
FileWriter writer = new FileWriter(file1);
writer.write(username + "," + password);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("登录成功!");
} else {
System.out.println("登录失败,请检查用户名和密码!");
}
}
private static void saveAccount(String username, String password) {
File file = new File("D:\\kecheng\\month316\\src\\wenjian\\userInfo1.txt");
try {
FileWriter writer = new FileWriter(file);
writer.write(username + "," + password);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static boolean checkAccount(String username, String password) {
File file = new File("D:\\kecheng\\month316\\src\\wenjian\\userInfo1.txt");
if (!file.exists()) {
return false;
}
try {
Scanner scanner = new Scanner(file);
String line = scanner.nextLine();
String[] parts = line.split(",");
String savedUsername = parts[0];
String savedPassword = parts[1];
scanner.close();
boolean T;
T= username.equals(savedUsername) && password.equals(savedPassword);
return T;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
}
/**在这个程序中,首先提示用户输入用户名和密码,并将这些信息保存到文件中。然后,程序要求用户重新输入用户名和密码,并比对这些信息是否与之前保存的信息匹配。如果匹配,则登录成功,否则登录失败。
在保存账户信息的方法中,我们使用Java的FileWriter类将用户名和密码写入文件中。在比对账户信息的方法中,我们使用Java的Scanner类读取文件内容,并使用String的split()方法将用户名和密码分开。最后,我们比对输入的用户名和密码是否与之前保存的信息匹配。
请注意,这个程序的保存方式并不安全,因为它将用户名和密码明文保存在文件中。在实际应用中,我们应该使用更安全的方式,例如哈希和加盐。
*/
9.拷贝图片
拷贝一张图片,从一个目录到另外一个目录下(PS:是拷贝是不是移动)
/**
* 拷贝一张图片,从一个目录到另外一个目录下(PS:是拷贝是不是移动)
* @author Administrator
* 1)在目的地址创建一个图片文件
2)读取源地址文件的字节流
3)把读取到的字节流写入到目的地址的文件里面
4)刷新输出流,并关闭就可以了
*/
public class Test {
public static void main(String[] args) {
//1.1 创建图片存放路径
File filefrom=new File("D:/c/c1/picture.jpg");
//1.2 创建图片移动后存放的路径
File fileto=new File("D:/c/c2/picture.jpg");
InputStream input=null;
OutputStream output=null;
try {
//将原本图片文件路径作为输入流
input=new FileInputStream(filefrom);
//将移动后图片路径作为输出流
output=new FileOutputStream(fileto);
byte[] by=new byte[1024];
//遍历读写
try {
while(input.read()!=-1){
output.write(by);
}
output.flush();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally{
try {
//关闭流
input.close();
output.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("拷贝成功!!");
}
}