java IO

作者: setone | 来源:发表于2018-11-14 18:09 被阅读0次

1 File 类可以用于表示文件和目录的信息,但是它不表示文件的内容。

FileInputStream和FileOutputStream的简单操作
将1.txt文件下的参数复制到2.txt里面

    @Test
    public void readText() throws FileNotFoundException {
        String path = "E:\\dir\\";
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File file = new File(dir, "1.txt");
        FileInputStream in = new FileInputStream(file);
        FileOutputStream out = new FileOutputStream(new File(dir, "2.txt"));
        try {
            byte[] buf = new byte[2];//缓冲区大小字节为2
            int by = 0;
            while ((by= in.read(buf))!= -1) {
                err.println("length::"+by+"==========buf::"+new String(buf));
                out.write(buf,0,by);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            if(in != null && out != null) {
                try {
                    in.close();
                    out.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

nio复制文件

@Test
    public void nioCopy() throws IOException {
        String path = "E:\\copy\\";
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File file = new File(dir, "mutual_finance.7z");

        /* 获得源文件的输入字节流 */
        FileInputStream fin = new FileInputStream(file);

        /* 获取输入字节流的文件通道 */
        FileChannel fcin = fin.getChannel();

        /* 获取目标文件的输出字节流 */
        FileOutputStream fout = new FileOutputStream(new File(dir, "mutual_finance2.7z"));

        /* 获取输出字节流的文件通道 */
        FileChannel fcout = fout.getChannel();

        /* 为缓冲区分配 1024 个字节 */
        ByteBuffer buffer = ByteBuffer.allocateDirect(1024);

        long start = System.currentTimeMillis();
        while (true) {
            /* 从输入通道中读取数据到缓冲区中 */
            int r = fcin.read(buffer);
            err.println("r::"+r);
            /* read() 返回 -1 表示 EOF */
            if (r == -1) {
                break;
            }

            /* 切换读写 */
            buffer.flip();

            /* 把缓冲区的内容写入输出文件中 */
            fcout.write(buffer);

            /* 清空缓冲区 */
            buffer.clear();
        }
        long end = System.currentTimeMillis();
        err.println("耗时"+(end - start)/1000);
    }

相关文章

网友评论

      本文标题:java IO

      本文链接:https://www.haomeiwen.com/subject/zmajfqtx.html