现在使用的是FileInputStream和FileOutputStream来实现文件夹的拷贝,当文件比较少的时候还可以,如果文件比较多比较大的时候(测试了一个2.2G左右的文件夹)机器就会比较卡,而且在GUI中调用会引起无响应。查看硬盘的读写速度最高17M/s左右,cpu占用率不高,在10%以下。我想能不能降低硬盘读写速率,我以前用的方法是读取5M数据后就sleep30毫秒,结果不理想,有时候拷贝速度比不sleep的还要快。有没有什么其他的办法呢?尽量的减少磁盘的读写速度,但是要在能接受的范围之内,可以适当的提高cpu的使用率~

解决方案 »

  1.   

                    FileInputStream fin = null;
    FileOutputStream fout = null;
    try {
    fin = new FileInputStream(sourceFile);
    fout = new FileOutputStream(goalFile);
    byte[] bytes = new byte[8092];
    int i = fin.read(bytes);
    int count = 0;
    while (i != -1) {
    count += 1;
    fout.write(bytes, 0, i);
    // if (count == 5 * 1024) {
    //
    // count = 0;
    // try {
    // Thread.sleep(30);// copy 1k then sleep 0.015s
    // } catch (InterruptedException e) {
    // // TODO Auto-generated catch block
    // e.printStackTrace();
    // }
    // }
    i = fin.read(bytes); }
    try {
    Thread.sleep(20);
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    } catch (FileNotFoundException e) {
    log.error("FileNotFoundException is happen " + e.getMessage());
    return false; } catch (IOException e) {
    log.error("IOException is happen " + e.getMessage());
    return false; } finally {
    try {
    fin.close();
    fout.close();
    goalFile.setLastModified(sourceFile.lastModified());
    } catch (Exception e) {
    log.error("Exception is happen " + e.getMessage());
    e.printStackTrace();
    } }
      

  2.   

    FileInputStream fin = null;
    FileOutputStream fout = null;
    try {
    fin = new FileInputStream(sourceFile);
    fout = new FileOutputStream(goalFile);
    byte[] bytes = new byte[8092];
    int i = fin.read(bytes);
    int count = 0;
    while (i != -1) {
    count += 1;
    fout.write(bytes, 0, i);
    // if (count == 5 * 1024) {
    //
    // count = 0;
    // try {
    // Thread.sleep(30);// copy 1k then sleep 0.015s
    // } catch (InterruptedException e) {
    // // TODO Auto-generated catch block
    // e.printStackTrace();
    // }
    // }
    i = fin.read(bytes); }
    try {
    Thread.sleep(20);
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    } catch (FileNotFoundException e) {
    log.error("FileNotFoundException is happen " + e.getMessage());
    return false; } catch (IOException e) {
    log.error("IOException is happen " + e.getMessage());
    return false; } finally {
    try {
    fin.close();
    fout.close();
    goalFile.setLastModified(sourceFile.lastModified());
    } catch (Exception e) {
    log.error("Exception is happen " + e.getMessage());
    e.printStackTrace();
    } }