1.在你的D盘下创建一个文件夹lx然后在里面创建一个名字叫abc.txt的文件,然后再修改他的名字为fly.txt
看代码不看文件
package com.sj.homework;
import java.io.File;
import java.io.IOException;
public class Test {
public static void main(String[] args) throws IOException {
String path = "D:/lx/abc.txt";//路径
String secondPath = "D:/lx/fly.txt";
WenJian wj = new WenJian();
wj.chuangJian(path);
// wj.shanChu(path);
wj.chongMingMing(path, secondPath);
}
}
package com.sj.homework;
import java.io.File;
import java.io.IOException;
public class WenJian {
//创建文件
public void chuangJian(String path) throws IOException {
File file = new File(path);//文件类
if (file.exists()) {//如果文件存在
System.out.println("文件存在");
} else {
System.out.println("文件不存在");
if (file.isDirectory()) {//如果路径存在
System.out.println("路径存在");
} else {
System.out.println("路径不存在");
//创建路径
String[] pathArray = path.split("/");
//把数组除了最后一个元素,其他元素累加在一起
String newPath = "";
for (int i = 0; i < pathArray.length-1; i++) {
newPath+=pathArray[i]+"/";
}
System.out.println("文件夹路径:"+newPath);
file = new File(newPath);
file.mkdirs();//创建文件夹,按照规定好的路径创建文件夹
System.out.println("文件夹创建成功!");
file = new File(path);
file.createNewFile();//创建文件
System.out.println("文件创建成功!");
}
}
}
//删除文件
public void shanChu(String path){
File file = new File(path);
file.delete();
System.out.println("文件删除成功!");
}
//重命名文件
public void chongMingMing(String path,String secondPath){
File file = new File(path);
File f2 = new File(secondPath);
file.renameTo(f2);
System.out.println("重命名成功!");
}
}
2.匹配验证-验证Email是否正确
package com.sj.homework;
public class Promise {
public String yzEmail(String email){
String regex = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
if (email.matches(regex)) {
return "你的邮箱为:"+email;
} else {
return "你输入的邮箱不正确";
}
}
}
package com.sj.homework;
import java.util.Scanner;
/**
* @desc 验证email
* @author ws
* @time 8.8
*/
public class Test3 {
public static void main(String[] args) {
System.out.print("请输入你的邮箱:");
Scanner cin = new Scanner(System.in);
String email = cin.nextLine();
Promise ps = new Promise();
System.out.println(ps.yzEmail(email));
}
}
3.请输入一行字符串,然后用正则表达式的方式去获取字符串中的数字,然后将他们求和输出在控制台上
package com.sj.homework;
//2.请输入一行字符串,然后用正则表达式的方式去获取字符串中的数字,然后将他们求和输出在控制台上
public class Promise2 {
public int yzString(String str){
String regex = "[^0-9]+";//正则表达式
String result = str.replaceAll(regex, "");//数字之外的改为空
char[] arr = result.toCharArray();
int he=0;
for (int i = 0; i < arr.length; i++) {
he+=arr[i]-'0';//char转int
}
return he;//返回数字之和
}
}
package com.sj.homework;
/**
* @desc 验证String
* @author ws
* @time 8.8
*/
public class Test4 {
public static void main(String[] args) {
Promise2 ps = new Promise2();
String str = "123asd126,./";
System.out.println(ps.yzString(str));
}
}