Java IO流上机练习
目录
把指定目录下(包含子目录)的所有图片,复制到另一个指定目录下
模拟用户登录功能实现。接收用户输入的用户名和密码,然后和文件中存储的用户名、密码匹配
在c盘下有篇txt文本,读取这个文本并统计出这个文本中指定字符的个数(如指定字符为”我”),将该字符与对应的次数输出到当前项目的key.txt中,例如:输出格式为:我=10
- 已知文件a.txt文件中的内容为“AAbcdea22dferwplkCC321ou1”,请编写程序读取该文件内容,要求去掉重复字母(区分大小写字母)并按照自然排序顺序后输出到b.txt文件中。即b.txt文件内容应为"abc......123..."这样的顺序输出
package com.exec;
import java.io.*;
import java.util.Arrays;
public class Homework4{
public static void main(String[] args) throws IOException {
BufferedReader br=new BufferedReader(new FileReader("a.txt"));
BufferedWriter bw=new BufferedWriter(new FileWriter("b.txt"));
String line=null;
StringBuffer sb=new StringBuffer();
while((line=br.readLine())!=null){
sb.append(line);
}
String str=sb.toString();
char[]buf=str.toCharArray();
Arrays.sort(buf);//排序
String s=new String(buf);
bw.write(s.replaceAll("(.)\\1+","$1"));
bw.flush();
}
}
- 把指定目录下(包含子目录)的所有图片,复制到另一个指定目录下
package com.exec;
import java.io.*;
public class HomeWork5 {
static String regex = ".+\\.([j][p][g]|[p][n][g]|[g][i][f]|[b][m][p])";
public static void main(String[] args) throws IOException {
File file = new File("D:\\images");
copyPhoto(file);
System.out.println("传输完成!");
}
/**
* 该方法是递归调用
* @param file
* @throws IOException
*/
private static void copyPhoto(File file) throws IOException {
File[] files = file.listFiles();
for (File file2 : files) {
if (file2.isDirectory()) {
copyPhoto(file2);
} else if (file2.getName().matches(regex)) {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file2));
byte[] buf = new byte[1024];
int length = 0;
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("D:\\aa\\" + file2.getName()));
while ((length = bis.read(buf)) != -1) {
bos.write(buf, 0, length);
}
bos.close();
bis.close();
}
}
}
}
- 模拟用户登录功能实现。接收用户输入的用户名和密码,然后和文件中存储的用户名、密码匹配
package com.exec; import java.io.*; import java.util.Scanner; /** * 模拟用户登录功能实现。接收用户输入的用户名和密码,然后和文件中存储的用户名、密码匹配 */ public class LoginSystem { //静态代码块,只会执行一次 static { File file = new File("D:\\aa\\config.properties"); try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } static Scanner input = new Scanner(System.in); public static void main(String[] args) throws Exception { while (true) { System.out.println("请选择功能 A:注册 B:登录"); String s = input.next(); if ("a".equalsIgnoreCase(s)) { // 注册 register();//文件写入过程 } else if ("b".equalsIgnoreCase(s)) { // 登录 login();//文件的读取操作 break; } else {