【java】文件读写拷贝等基本操作

// ------拷贝操作-------
        // 源文件path
        File targetFile = new File("/Users/aionyiruma/Desktop/file测试/newnew.txt");
        // 副本所在path
        File copyFile = new File("/Users/aionyiruma/Desktop/file测试/copy_newnew.txt");
        // 拷贝操作
        try ( //声明自动关闭变量,省去close操作
                InputStream inputStream = new FileInputStream(targetFile);
                // true:末尾追加 false:覆盖
                OutputStream outputStream = new FileOutputStream(copyFile, false);) {

            byte[] targetBytes = new byte[10];
            int length = inputStream.read(targetBytes);
            while (length != -1) {
                // 只要还有数据 就往临时数组里添加 直到返回-1
                                outputStream.write(targetBytes);
                length = inputStream.read(targetBytes);
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }

        // ------读取操作------
        try (InputStream inputStream = new FileInputStream(targetFile);) {// 创建一个二进制流数组
            byte[] arr = new byte[5];
            // 当inputStream.read(arr))方法返回-1时,表示已经读取完毕
            int length = -1;
            while ((length = inputStream.read(arr)) != -1) {
                // 将的unicode编码解析成字符串
                String string = new String(arr, 0, length);
                System.out.println(string);
            }

        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

        // ------写入操作------
        try (OutputStream outputStream = new FileOutputStream(targetFile, true);) {

            outputStream.write("1234567".getBytes(), 2, 4);

        } catch (Exception e) {
            e.printStackTrace();
        }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容