zoukankan      html  css  js  c++  java
  • IOTest-InputStream-OutputStream

    //大文件复制 包装前后 时间测试
    @Test
    public void copyTest() throws Exception{
    long start = System.currentTimeMillis();
    //读取文件c:centos.iso
    FileInputStream fis = new FileInputStream("c:\centos.iso");
    BufferedInputStream bis = new BufferedInputStream(fis);
    FileOutputStream fos = new FileOutputStream("d:\cent.iso");
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    int len = 0;
    byte[] buf = new byte[4096];
    while((len = bis.read(buf))!=-1){
    bos.write(buf, 0, len);
    }
    bis.close();
    bos.close();
    long end = System.currentTimeMillis();
    System.out.println("复制所用时间:"+(end - start));//1024-11592 //4096-8046
    }

     ---------------------------

    //复制文件c:hz.txt 到 d:hz2.txt
    @Test
    public void copyFile() throws IOException{
    //首先创建一个hz.txt文件在c盘
    File f = new File("c:\hz.txt");
    f.createNewFile();
    //向文件当中写入数据
    String str = "Hello 你好 Java ";
    Writer wr = new FileWriter(f,true);
    // wr.write(str);
    // wr.flush();
    // wr.close();
    //读取文件到内存 并写入d盘
    Reader rd = new FileReader(f);
    int len = 0;
    char[] buf = new char[1024];
    while((len = rd.read(buf))!=-1){
    wr = new FileWriter("d:\hz2.txt",true);
    // wr.write(buf, 0, len);
    wr.write(new String(buf));
    }
    wr.flush();
    wr.close();
    }

    ------------------------------

    public class IOTest {
    static File f = new File("a.txt");
    public static void main(String[] args) {
    m2();
    }
    public static void m2(){
    InputStream in = null;
    int len = 0;
    byte[] buf;
    buf = new byte[100];
    try {
    in = new FileInputStream(f);//读取文件
    len = in.read(buf);
    System.out.println(len);//读取的内容长度
    System.out.println(new String(buf));//读取的内容
    } catch (FileNotFoundException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    public static void m1(){
    OutputStream out = null;
    String str = "ABC012国 ";
    byte[] buf = null;
    try {
    buf = str.getBytes("utf-8");//把写入内容指定字符集 防止乱码
    //out = new FileOutputStream(f);//覆盖写入文件
    out = new FileOutputStream(f,true);//追加写入文件
    out.write(buf);
    } catch (FileNotFoundException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    }finally{
    try {
    out.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    }
    }//main

  • 相关阅读:
    用Java来获取访问者真实的IP地址
    springMVC 配置多个视图解析器
    java 内部类(inner class)详解
    安装mysql步骤
    Jquery 获取父页面下指定iframe里的指定元素
    Oracle 中文排序
    Oracle update时做表关联
    Jquery IE8兼容性
    JQuery 动态创建表单,并自动提交
    JQuery 使用.show()和.hide()做的可爱动画
  • 原文地址:https://www.cnblogs.com/geryhz/p/14326381.html
Copyright © 2011-2022 走看看