Java文件操作和IO

读取文件中的内容:

将文件完全读完的两种方式:

  1. 方式1

    public static void main(String[] args) {

        // 创建流对象(try-catch-resource) JDK1.7

        try (InputStream inputStream = new FileInputStream("b.txt")) {

            // 读写操作

            while (true) {

                int c = inputStream.read();

                if (c == -1) break;

                Thread.sleep(200);

                System.out.printf("%c", c);

            }

        } catch (InterruptedException | IOException e) {

            e.printStackTrace();

        }

    }



  1. 方式2

    public static void main(String[] args) {

        try (InputStream inputStream = new FileInputStream("b.txt")) {

            byte[] bytes = new byte[1024];

            while (true) {

                // 如果数据超过了byte容量,会读取多次

                int c = inputStream.read(bytes);

                if (c == -1) break;

                System.out.println(new String(bytes, StandardCharsets.UTF_8));

                Thread.sleep(200);

            }

        } catch (InterruptedException | IOException e) {

            e.printStackTrace();

        }

    }



3.1.3 使用Scanner进行数据读取

可以使⽤Scanner进行数据读取,它有一个构造方法:

在这里插入图片描述

示例:


    public static void main(String[] args) {

        try (InputStream inputStream = new FileInputStream("b.txt")) {

            try (Scanner scanner = new Scanner(inputStream, "utf-8")) {

                while (scanner.hasNext()) {

                    System.out.println(scanner.nextLine());

                }

            }

        } catch (IOException e) {

            e.printStackTrace();

        }

    }



3.2 OutputStream:输出流


OutputStream 输出流是进行数据写入的。

3.2.1 OutputStream常用方法

在这里插入图片描述

说明:

OutputStream 同样只是一个抽象类,要使用还需要具体的实现类。我们现在还是只关心写入文件中,所以使用 FileOutputStream

3.2.2 实现数据写入

一个一个字符写入:


    public static void main(String[] args) throws IOException {

        File file = new File("c.txt");

        if (!file.exists()) System.out.println("新建文件:" + file.createNewFile());

        // 写入数据

        try (OutputStream outputStream = new FileOutputStream(file)) {

            outputStream.write('h');

            outputStream.write('e');

            outputStream.write('l');

            outputStream.write('l');

            outputStream.write('o');

            outputStream.flush();

        }

    }



字节数组批量写入:


    public static void main(String[] args) throws IOException {

        File file = new File("c.txt");

        if (!file.exists()) System.out.println("创建文件:" + file.createNewFile());

        // 写入数据

        try (OutputStream outputStream = new FileOutputStream(file)){

            byte[] bytes = new byte[]{

                    'h', 'e', 'e'

            };

            outputStream.write(bytes);

            outputStream.flush();

        }

    }



字符串写入:


    public static void main(String[] args) throws IOException {

        File file = new File("c.txt");

        if (!file.exists()) System.out.println("创建文件:" + file.createNewFile());

        // 写入数据

        try (OutputStream outputStream = new FileOutputStream(file)) {

            String msg = "hello, world";

            outputStream.write(msg.getBytes(StandardCharsets.UTF_8));

            outputStream.flush();

        }

    }



3.2.3 使用PrintWriter进行写入

除了上述的写入方式之外,JDK还提供了一个类 PrintWriter 可以很方便的实现数据写入。 PrintWriter类中提供了我们熟悉的 print/println/printf 方法。

示例:


    public static void main(String[] args) throws IOException {

        File file = new File("c.txt");

        if (!file.exists()) {

            System.out.println("创建文件:" + file.createNewFile());

        }

        try (PrintWriter printWriter = new PrintWriter(file)) {

            printWriter.println("这是第一行数据");

            printWriter.println("这是第二行数据");

            printWriter.flush();

        }

    }



3.2.4 使用FileWriter追加数据

示例:


    public static void main(String[] args) throws IOException {

        File file = new File("c.txt");

        if (!file.exists()) System.out.println("创建文件:" + file.createNewFile());

        // 数据追加

        try (FileWriter fileWriter = new FileWriter(file, true)) {

            fileWriter.append("\n我是追加的数据");

            fileWriter.flush();

        }

    }



4.练习

===================================================================

示例1


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


public class Main {

    public static void main(String[] args) throws IOException { 

        Scanner scanner = new Scanner(System.in);

        System.out.print("请输入要扫描的根目录(绝对路径 OR 相对路径): "); 

        String rootDirPath = scanner.next();

        File rootDir = new File(rootDirPath); 

        if (!rootDir.isDirectory()) {

            System.out.println("您输入的根目录不存在或者不是目录,退出"); 

            return;

        }

        System.out.print("请输入要找出的文件名中的字符: "); 

        String token = scanner.next();

        List<File> result = new ArrayList<>();

        // 因为文件系统是树形结构,所以我们使用深度优先遍历(递归)完成遍历 

        scanDir(rootDir, token, result);

        System.out.println("共找到了符合条件的文件 " + result.size() + " 个,它们分别 

是");

        for (File file : result) {

            System.out.println(file.getCanonicalPath() + "    请问您是否要删除该文 

件?y/n");

            String in = scanner.next();

            if (in.toLowerCase().equals("y")) { 

                file.delete();

            } 

        }

    }

    private static void scanDir(File rootDir, String token, List<File> result) { 

        File[] files = rootDir.listFiles();

        if (files == null || files.length == 0) { 

            return;

        }

        for (File file : files) {

            if (file.isDirectory()) {

                scanDir(file, token, result); 

            } else {

                if (file.getName().contains(token)) { 

                    result.add(file.getAbsoluteFile()); 

                }

            } 

        } 

    }

}



示例2


进行普通文件的复制。


public class Main {

    public static void main(String[] args) throws IOException { 

        Scanner scanner = new Scanner(System.in);

        System.out.print("请输入要复制的文件(绝对路径 OR 相对路径): "); 

        String sourcePath = scanner.next();

        File sourceFile = new File(sourcePath); 

        if (!sourceFile.exists()) {

            System.out.println("文件不存在,请确认路径是否正确"); 

            return;

        }

        if (!sourceFile.isFile()) {

            System.out.println("文件不是普通文件,请确认路径是否正确"); 

            return;

        }

        System.out.print("请输入要复制到的目标路径(绝对路径 OR 相对路径): "); 

        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("目录路径已经存在,是否要进行覆盖?y/n"); 

                String ans = scanner.next();

                if (!ans.toLowerCase().equals("y")) { 

                    System.out.println("停止复制"); 

                    return;

                } 

            } 

        }

        try (InputStream is = new FileInputStream(sourceFile)) {

            try (OutputStream os = new FileOutputStream(destFile)) { 

                byte[] buf = new byte[1024];

                int len;

                while (true) {

                    len = is.read(buf); 

                    if (len == -1) { 

                        break;

                    }

                    os.write(buf, 0, len); 

                }

                os.flush(); 

            }

        }

        System.out.println("复制已完成"); 

    }

}



示例3


扫描指定目录,并找到名称或者内容中包含指定字符的所有普通文件(不包含目录)。


public class Main {

    public static void main(String[] args) throws IOException { 

        Scanner scanner = new Scanner(System.in);

        System.out.print("请输入要扫描的根目录(绝对路径 OR 相对路径): "); 

        String rootDirPath = scanner.next();

        File rootDir = new File(rootDirPath); 

        if (!rootDir.isDirectory()) {

            System.out.println("您输入的根目录不存在或者不是目录,退出"); 

            return;

        }

        System.out.print("请输入要找出的文件名中的字符: "); 

        String token = scanner.next();

        List<File> result = new ArrayList<>();

        // 因为文件系统是树形结构,所以我们使用深度优先遍历(递归)完成遍历 

        scanDirWithContent(rootDir, token, result);

        System.out.println("共找到了符合条件的文件 " + result.size() + " 个,它们分别 

是");

        for (File file : result) {

            System.out.println(file.getCanonicalPath()); 

        }

    }

    private static void scanDirWithContent(File rootDir, String token, 

List<File> result) throws IOException {

        File[] files = rootDir.listFiles();

        if (files == null || files.length == 0) { 

            return;

        }

        for (File file : files) {

            if (file.isDirectory()) {

                scanDirWithContent(file, token, result); 

            } else {

                if (isContentContains(file, token)) { 

                    result.add(file.getAbsoluteFile()); 

                }

            } 

        }

    }

    // 我们全部按照utf-8的字符文件来处理

    private static boolean isContentContains(File file, String token) throws 

IOException {

        StringBuilder sb = new StringBuilder();

        try (InputStream is = new FileInputStream(file)) {

            try (Scanner scanner = new Scanner(is, "UTF-8")) { 

                while (scanner.hasNextLine()) {

                    sb.append(scanner.nextLine()); 

                    sb.append("\r\n");

                } 

            } 

        }

        return sb.indexOf(token) != -1; 

    }

}



最后

由于篇幅限制,小编在此截出几张知识讲解的图解

P8级大佬整理在Github上45K+star手册,吃透消化,面试跳槽不心慌

P8级大佬整理在Github上45K+star手册,吃透消化,面试跳槽不心慌

P8级大佬整理在Github上45K+star手册,吃透消化,面试跳槽不心慌

P8级大佬整理在Github上45K+star手册,吃透消化,面试跳槽不心慌

P8级大佬整理在Github上45K+star手册,吃透消化,面试跳槽不心慌

b = new StringBuilder();

    try (InputStream is = new FileInputStream(file)) {

        try (Scanner scanner = new Scanner(is, "UTF-8")) { 

            while (scanner.hasNextLine()) {

                sb.append(scanner.nextLine()); 

                sb.append("\r\n");

            } 

        } 

    }

    return sb.indexOf(token) != -1; 

}

}




 


### 最后

**由于篇幅限制,小编在此截出几张知识讲解的图解**

[外链图片转存中...(img-ymzgV88S-1714374028655)]

[外链图片转存中...(img-yws93eSl-1714374028656)]

[外链图片转存中...(img-8cafNQeN-1714374028656)]

[外链图片转存中...(img-H8kKkTTC-1714374028656)]

[外链图片转存中...(img-RJRHExGz-1714374028657)]



> **本文已被[CODING开源项目:【一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码】](https://bbs.csdn.net/topics/618154847)收录**
  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值