如何在线程中上传文件而不中断其他工作?

时间:2012-10-04 09:45:41

标签: java

我通过编写此代码

在线程中上传文件
import java.io.*;
public class FileUploadThread extends Thread {

    File f1, f2;
    String fileName;
    InputStream stream;
    byte[] b = new byte[1024];

    public FileUploadThread(File f1, File f2, InputStream stream, String filename) {
        System.out.println("external class file name--->" + filename);
        this.f1 = f1;
        this.f2 = f2;
        this.stream = stream;
        this.fileName = filename;
    }

    public void run() {
        try {
            f2 = new File(f1, fileName);
            OutputStream w = new FileOutputStream(f2);

            int res = stream.read(b);
            System.out.println("res = "+res);
            while (res >= 0) {
                for (int i = 0; i < res; i++) {
                    w.write(b);
                }
              res = stream.read(b);
              System.out.println("res--->" + res);
            }

        } catch (Exception e) {
            System.out.println("In the run method of the thread");
            e.printStackTrace();
        }
    }

}

它显示了ArrayIndexOutOfBoundsException

2 个答案:

答案 0 :(得分:1)

尝试使用w.write(b, 0, res)

您使用的方法实际上是调用w.write(b, 0, b.length),但读取最多可以返回b.length个字节

<强>更新

你的副本循环看起来应该更像......

OutputStream w = null;
try {
    f2 = new File(f1, fileName);
    w = new FileOutputStream(f2);

    int res = -1;
    while ((res = stream.read(b)) != -1) {
        w.write(b, 0, res);
    }

} catch (Exception e) {
    System.out.println("In the run method of the thread");
    e.printStackTrace();
} finally {
    try {
        w.close();
    } catch (Exception e) {
    }
}

不要忘记,如果你打开一个流,你有责任关闭它......

答案 1 :(得分:0)

我不知道你的情况如何,但它对我来说效果很好。我对这个计划有两点建议:

1.由于您在运行函数中将f2引用指定为f2 = new File(f1, fileName);,为什么要在构造函数中传递另一个File参数File f2?据我所知,构造函数中的f2参数是无用的。

2.您不需要for循环来编写。一旦调用w.write(b),它实际上会刷新b中的所有字节,然后写入f2。