import java.io.*;
public class lianxi_1_9 {
public static void main(String[] args) throws IOException {
File file = new File("D:\\java2211\\练习需要的文件");
// test1();
// deleteFile(file);
// test1_2(file);
// test2();
// test2_2();
// test3();
// test3_2();
}
private static void deleteFile(File file) {
}
// 1. 使用File类相关的方法 ,编写删除文件夹的方法
// 要求:既能删除空文件夹 也能删除非空文件夹
//
public static void test1(File file) {
File[] allFile = file.listFiles();
for (File f : allFile) {
if (f.isFile()) {
f.delete();
} else {
test1(f);
}
}
file.delete();
}
public static void test1_2(File file){
if (file.exists()){//查看文件是否存在 如果不存在则 输入文件夹不存在
if (file.isFile()){//是文件 直接删除
file.delete();//删除文件
}else {//获取遍历
File[] files = file.listFiles();
if (files.length!=0){
for (File f:files){
test1_2(f);
}
file.delete();// 上面的for循环能删除所有文件 剩下空文件夹 删除即可
}else {//空文件夹 删除
file.delete();
}
}
}else{
System.out.println("文件不存在");
}
}
// 2. 使用绝对路径,在D盘创建一个testIO文件夹,然后再testIO文件中创建一个1.txt文件中;
// 使用相对路径,在当前项目下创建一个testIO文件夹,然后再testIO文件中创建一个2.txt文件中
//
public static void test2() {
File file = new File("D:\\testIO\\1.txt");
File files = new File("D:\\java2211\\HomeWork\\testIO\\2.txt");
}
public static void test2_2() throws IOException {
File file=new File("D:\\testIO");
file.mkdir();
File file1=new File(file,"1.txt");
file1.createNewFile();
File file2=new File("testIO");
file1.mkdir();
File file3=new File(file2,"2.txt");
file3.createNewFile();
}
// 3. 文件夹的复制
// 提示:结合 File类 和 字节输入输出流 相关的方法
public static void test3() throws IOException {
FileReader fr= new FileReader("D:\\java2211");
FileWriter fw=new FileWriter("D:");
char[] cs = new char[1024];
int readNum = -1;//实际上读取到的字符的个数
while ((readNum = fr.read(cs)) != -1) {
String str = new String(cs, 0, readNum);
fw.write(str);
}
fr.close();
fw.close();
}
public static void test3_2(File src,File target) throws IOException {
if (src.isFile()){
FileInputStream fis=new FileInputStream(src);
FileOutputStream fos=new FileOutputStream(target);
int readByte=-1;
while ((readByte=fis.read())!=-1){
fos.write(readByte);
}
fis.close();
fos.close();
}else {
target.mkdir();
File[]files=src.listFiles();
for(File f:files){
File targetFile=new File(target,f.getName());
copuDir(f,targetFile);
}}
}
private static void copuDir(File f, File targetFile) {
}
}