Io字节流

该博客详细展示了如何使用Java的Io字节流实现文件复刻,通过 FileInputStream 和 FileOutputStream 进行数据读写。同时,文章探讨了如何随机生成文本文件、将Java源代码文件合并到Markdown文档中,并提供了比较两个文件字节内容是否相同的方法。此外,还介绍了如何判断文件的真实类型,通过检查文件头几个字节来识别常见文件格式。
摘要由CSDN通过智能技术生成

Io字节流

实现文件复刻

public static void main(String[] args) {
    //实现文件复刻
    try (var a = new FileInputStream("D:/develop/abc/12.png");
         var b = new FileOutputStream("D:/develop/abc/1.jpg")) {
        int len = 0;
        while ((len = a.read()) != -1) {
            b.write(len);
        }
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    try (FileInputStream fis = new FileInputStream("D:/develop/abc/12.png")) {
        byte[] buf = new byte[10];
        fis.skip(fis.available());
        int lan = fis.read(buf);
        System.out.println(Arrays.toString(buf));
        System.out.println(lan);
    } catch (IOException e) {
    }

    try (FileInputStream fis = new FileInputStream("D:/develop/abc/12.png")) {
        for (int i = 0; i < 10; i++) {
            int t = fis.read();
            System.out.printf("%03d ", t);
        }
    } catch (IOException e) {
    }
    System.out.println();
    try (FileInputStream fis = new FileInputStream("D:/develop/abc/1.jpg")) {
        for (int i = 0; i < 10; i++) {
            int t = fis.read();
            System.out.printf("%03d ", t);
        }
    } catch (IOException e) {
    }
}

public static void test(String[] args) {
    try (FileInputStream fis = new FileInputStream("D:/develop/abc/12.png")) {
        int i = fis.read();
        System.out.println(i);
        fis.skip(2000);
        i = fis.read();
        System.out.println(i);
    } catch (IOException e) {
    }
    try (FileInputStream fis = new FileInputStream("D:/1develop/abc/1.jpg")) {
        int i = fis.read();
        System.out.println(i);
        fis.skip(2000);
        i = fis.read();
        System.out.println(i);
    } catch (IOException e) {

    }
}

随机生成一个文本文件

public static void main(String[] args) {
    //随机生成一个文本文件
    Random rand = new Random();
    try (var os = new FileOutputStream("my.txt", true)) {
        for (int i = 0; i < 1000; i++) {
            os.write(randStr(rand.nextInt(2, 20)).concat("\r\n").getBytes());
        }
    } catch (Exception e) {

    }
}

public static String randStr(int n) {
    Random rand = new Random();
    String letter = "abcdefghijklmnopqrstuvwxyz";
    StringBuffer sbu = new StringBuffer();
    for (int i = 0; i < n; i++) {
        StringBuilder sbu2 = new StringBuilder();
        int len = rand.nextInt(2, 21);
        for (int j = 0; j < len; j++) {
            sbu2.append(letter.charAt(rand.nextInt(letter.length())));
        }
        sbu2.append(" ");
        String ts = sbu2.toString();
        if (i == 0) {
            ts = ts.substring(0, 1).toUpperCase().concat(ts.substring(1));
        } else if (i == n - 1) {
            ts = ts.substring(0, ts.length() - 1) + "!.?".charAt(rand.nextInt(3));
        }
        sbu.append(ts);
    }
    return sbu.toString();
}

把Java文件合成到md里面

static int num = 0;
public static void main(String[] args) {
    //把Java文件合成到md里面
    all(new File("D:\\develop\\java\\demo1\\JSE2022"));
}

public static void all(File dir) {
    if (dir.isDirectory()) {
        File[] fs = dir.listFiles();
        for (File f : fs) {
            if (f.isDirectory()) all(f);
            if (f.isFile() && f.getName().endsWith(".java")) {
                all(++num, f, new File("src.md"));
            }
        }
    }
    if (dir.isFile() && dir.getName().endsWith(".java")) {
        all(++num, dir, new File("src.md"));
    }
}

public static void all(int n, File src, File dst) {
    String template = """
            >%d、%s (%d行,日期: %tF %<tT)
            ```java
            %s
            ```
                            
            """;
    try (var is = new FileInputStream(src); var os = new FileOutputStream(dst, true)) {
        int num = n;
        String s = new String(is.readAllBytes());
        long rows = s.lines().count();
        String path = src.getAbsolutePath();
        String source = String.format(template, num, path, rows, src.lastModified(), s);
        System.out.println(source);
        os.write(source.getBytes());
        os.flush();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

比一下字节看看是不是同一个文件

 System.out.println(isSame(new File("D:/develop/abc/ca.java"), new File("D:/develop/abc/12.png")));
}
public static boolean isSame(String src, String dst) {
    return isSame(new File(src), new File(dst));
}

public static boolean isSame(File src, File dst) {
    boolean f = false;
    if (src.length() == dst.length()) {
        try (var issrc = new FileInputStream(src);
             var isdst = new FileInputStream(dst)) {
            int num = 0;
            while (issrc.read() == isdst.read()) {
                ++num;

                if (num == src.length()) {
                    f = true;
                    break;
                }
            }
        } catch (Exception e) {
        }
    }
    return f;
}

判断文件的真实类型

//判断文件的真实类型
    Map<String, Object> map = new HashMap<>();
    map.put("ffd8ffe1", "jpg");
    map.put("fd8ffeD", "png");
    map.put("504b34", "zip");
    map.put("52617221", "rar");

    System.out.println(getType(new File("D:/develop/abc/ca.java")));

   File dir = new File("D:/develop/abc");
    File[] files = dir.listFiles();
    for (File f : files) {
        String fn = f.getName();
        String ext = fn.substring(fn.lastIndexOf(".")).toLowerCase();
        System.out.printf("%s : %s :%S %n", fn, ext, getHeader(f, 10));
    }

}

public static String getType(File file) {
    Map<String, String> map = new HashMap<>();
    map.put("ffd8ffe1", "jpg");
    map.put("fd8ffeD", "png");
    map.put("504b34", "zip");
    map.put("52617221", "rar");
    String header = getHeader(file, 4);
    if (map.containsKey(header)) {
        return map.get(header);
    } else {
        return "未知文件";
    }
}

public static String getHeader(File src, int n) {
    String header = "";
    if (src.isFile()) {
        try (var is = new FileInputStream(src)) {
            byte[] buf = new byte[n];
            is.read(buf);
            StringBuffer sbu = new StringBuffer();
            for (byte b : buf) {
                sbu.append(String.format("%x", b));
            }
            header = sbu.toString();
        } catch (Exception e) {
        }
    } else {
        header = "不是文件";
    }
    return header;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值