Java文件流练习

发布于:2024-04-28 ⋅ 阅读:(18) ⋅ 点赞:(0)

1  扫描指定目录,并找到名称中包含指定字符的所有普通文件(不包含目录),并且后续询问用户是否要删除该文件

import java.io.File;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
     Scanner scanner=new Scanner(System.in);
     //先让用户输入一个目录
        System.out.println("请输入你要扫描的目录");
        String path=scanner.next();
        File file=new File(path);
        //验证输入合法性
        if(!file.isDirectory()){
            System.out.println("输入文件路径有误");
            return;
        }
        //让用户输入查询关键字
        System.out.println("请输入查询的关键字");
        String word=scanner.next();
        //开始扫描
        scanDir(file,word);
    }

    private static void scanDir(File file, String word) {
        if(file==null)return;
        //先列出file的目录和文件
        File[] path=file.listFiles();
        for (File f:path) {
            //日志
            System.out.println(f.getAbsolutePath());
            if(f.isFile()){
                //是文件,看看有没有包含关键字
                if(f.getName().contains(word)){
                    System.out.println("当前扫描的文件是"+f.getAbsolutePath()+"删除输入Y,不删除输入N");
                    String user=new Scanner(System.in).next();
                    if(user.equals("Y")||user.equals("y")){
                        f.delete();
                        System.out.println("删除成功");
                    }
                    else System.out.println("删除失败");
                }
            }
            else {
                scanDir(f,word);
            }
        }
    }
}

 

2  进行普通文件的复制

 

import java.io.*;
import java.util.Scanner;

//文件流操作
public class Main {
    public static void main(String[] args) throws IOException {
        Scanner scanner=new Scanner(System.in);
        System.out.print("请输入要复制的文件(绝对路径 OR 相对路径): ");// E:\Test\bbb\222.txt
        String souPath=scanner.next();
        File soutfile=new File(souPath);
        if(soutfile==null)return;
        if(!soutfile.exists()){
            System.out.println("文件不存在,请确认路径是否正确");
            return;
        }
        if(!soutfile.isFile()){
            System.out.println("输入有误");
            return;
        }
        System.out.println("请输入要复制到的目标目录");//E:\Test\aaa\222.txt
        String destPath=scanner.next();
        File destFile=new File(destPath);
        if(destFile.exists()){//不能直接复制到目录下,要输入目录+目标文件名字
            if(destFile.isDirectory()){
                System.out.println("目标路径已经存在,并且是一个目录,请确认路径是否正确");
                return;
            }
        }
        if(destFile.isFile()){
            System.out.println("目标文件已经存在");
            return;
        }
        try(InputStream is = new FileInputStream( soutfile)) {
            try(OutputStream os=new FileOutputStream(destFile)){
                Scanner sc=new Scanner(is);
                PrintWriter writer=new PrintWriter(destFile);
                writer.println(sc);
                writer.flush();
            }
        }
        System.out.println("复制成功");
    }
}

 


网站公告

今日签到

点亮在社区的每一天
去签到