显示了在Java小程序的FTP上传文件时进度 [英] Show progress during FTP file upload in a java applet

查看:196
本文介绍了显示了在Java小程序的FTP上传文件时进度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

OK,所以我必须使用Java FTP上传文件上传,我想更新标签和进度条。用百分比文本标签,用百分比int值吧。眼下与当前code只能得到在上载的最后100米和酒吧。在上载期间他们没有改变。

在这里它是:

 的OutputStream输出=新的BufferedOutputStream(ftpOut);
    CopyStreamListener监听器=新CopyStreamListener(){
        公共无效bytesTransferred(长totalBytesTransferred,诠释bytesTransferred,长streamsize可){
            System.out.printf(\\ r%-30S数:%d /%D,已发送,totalBytesTransferred,streamsize可);
            ftpup.this.upd(totalBytesTransferred,streamsize可);
        }
        公共无效bytesTransferred(CopyStreamEvent为arg0){}
    };    Util.copyStream(输入,输出,ftp.getBufferSize(),f.length(),侦听);
}公共无效UPD(NUM长,长尺寸){
    INT K =(INT)((NUM * 100)/尺寸);
    的System.out.println(将String.valueOf(K));
    this.d.setText(将String.valueOf(K));
    //d.setText(String.valueOf(k));
    progressBar.setValue(K);
}


解决方案

从它(和缺乏对contree任何证据)的声音听起来像你的处理耗时在的事件指派线程

您可能想在Swing 阅读并发一些进一步了解

我建议使用的SwingWorker 执行实际传输和放大器;趁其内置的进步支持

看了之后的更新源$ C ​​$ C


  1. 请不要使用重量轻组分混合重量级的组件。更改 Applet的 JApplet的,将文本字段的JTextField ,不使用画布使用的JP​​anel 的JComponent

  2. 如果您希望其他人读你的code,请用正确的名称为您的变量,我不知道是什么 P

  3. 是没用的。而不是启动线程,并使用它的运行方法,你只需让它的构造函数中您的下载呼叫。这会做什么你...

删除你的 MyThread的实施,以

替换

 公共类MyWorker扩展的SwingWorker<对象,对象> {    私人URL主机;
    私人文件OUTPUTFILE;    公共MyWorker(URL主机,文件f){
        this.host =主机;
        OUTPUTFILE = F;
    }    @覆盖
    保护对象doInBackground()抛出异常{        //你在给构造过去忽略了你的主机
        字符串主机=localhost的;
        字符串username =UN;
        字符串密码=通行证;
        字符串位置= f.toString();        // FTPClient FTP = NULL;        ftp.connect(主机名,2121);
        ftp.login(用户名,密码);        ftp.setFileType(FTP.BINARY_FILE_TYPE);        ftp.setKeepAlive(真);
        ftp.setControlKeepAliveTimeout(3000);
        ftp.setDataTimeout(3000); //100分钟
        ftp.setConnectTimeout(3000); //100分钟        ftp.changeWorkingDirectory(/ SSL);        INT回复= ftp.getReply code();
        的System.out.println(从FTP连接收到回复:+回复);        如果(FT preply.isPositiveCompletion(回复)){
            的System.out.println(连接成功);
        }
        的System.out.println(f.getName()的toString());        文件F1 =新的文件(位置);
        在=新的FileInputStream(F1);        输入的FileInputStream =新的FileInputStream(F1);
        // ftp.storeFile(f.getName()的toString()中);        // ProgressMonitorInputStream是=新ProgressMonitorInputStream(的getParent(),ST,上);
        OutputStream的ftpOut = ftp.storeFileStream(f.getName()的toString());
        的System.out.println(ftpOut.toString());
        // NEWNAME hereSystem.out.println(ftp.remoteRetrieve(f.toString()));
        OutputStream的输出=新的BufferedOutputStream(ftpOut);
        CopyStreamListener监听器=新CopyStreamListener(){
            公共无效bytesTransferred(最终长totalBytesTransferred,最终诠释bytesTransferred,最终长streamsize可){                setProgress((INT)Math.round(((双)totalBytesTransferred /(双)streamsize可)* 100D));            }            @覆盖
            公共无效bytesTransferred(CopyStreamEvent为arg0){
                // TODO自动生成方法存根
            }
        };        Util.copyStream(输入,输出,ftp.getBufferSize(),f.length(),侦听);        返回null;    }
}

在你的的ActionListener (?)取代线程执行code。与

  {尝试
    MyWorker工人=新MyWorker(新URL(HTTP:// localhost的),文件);
    worker.addPropertyChangeListener(新的PropertyChangeListener(){        @覆盖
        公共无效的propertyChange(PropertyChangeEvent的EVT){
            如果(evt.getPropertyName()。等于(进步)){
                整数进度=(整数)evt.getNewValue();
                progressBar.setValue(进度);
            }
        }
    });
    worker.execute();
}赶上(MalformedURLException的前){
    ex.printStackTrace();
}

请注意。您不理你传递给构造函数的URL。 HTTP://没有FTP://所以我怀疑这会工作...

OK so I have the uploader uploading files using the Java FTP, I would like to update the label and the progress bar. Label with the percent text, bar with the percent int value. Right now with the current code only get the 100 and full bar at the end of the upload. During the upload none of them change.

here it is:

    OutputStream output = new BufferedOutputStream(ftpOut);
    CopyStreamListener listener = new CopyStreamListener() {
        public void bytesTransferred(long totalBytesTransferred, int bytesTransferred, long streamSize) {
            System.out.printf("\r%-30S: %d / %d", "Sent", totalBytesTransferred, streamSize);
            ftpup.this.upd(totalBytesTransferred,streamSize);
        }
        public void bytesTransferred(CopyStreamEvent arg0) { }
    };

    Util.copyStream(input, output, ftp.getBufferSize(), f.length(), listener);      
}

public void upd(long num, long size){
    int k = (int) ((num*100)/size);
    System.out.println(String.valueOf(k));
    this.d.setText(String.valueOf(k));
    //d.setText(String.valueOf(k));
    progressBar.setValue(k);
}

解决方案

From the sounds of it (and lacking any evidence to the contree) it sounds like your processing a time consuming action in the Event Dispatching Thread

You might like to read Concurrency in Swing for some further insight

I'd suggest using a SwingWorker to perform the actual transfer & take advantage of its built in progress support

UPDATE after seeing source code

  1. Don't mix heavy weight components with light weight components. Change Applet to JApplet, change TextField to JTextField, don't use Canvas use a JPanel or JComponent
  2. If you expect other people to read your code, please use proper names for your variables, I have no idea what p is.
  3. Your Thread is useless. Rather then starting the thread and using it's run method you simply make your download call within it's constructor. This will do nothing for you...

Remove your implementation of MyThread and replace it with

public class MyWorker extends SwingWorker<Object, Object> {

    private URL host;
    private File outputFile;

    public MyWorker(URL host, File f) {
        this.host = host;
        outputFile = f;
    }

    @Override
    protected Object doInBackground() throws Exception {

        // You're ignoring the host you past in to the constructor
        String hostName = "localhost";
        String username = "un";
        String password = "pass";
        String location = f.toString();

        //FTPClient ftp = null;

        ftp.connect(hostName, 2121);
        ftp.login(username, password);

        ftp.setFileType(FTP.BINARY_FILE_TYPE);

        ftp.setKeepAlive(true);
        ftp.setControlKeepAliveTimeout(3000);
        ftp.setDataTimeout(3000); // 100 minutes
        ftp.setConnectTimeout(3000); // 100 minutes

        ftp.changeWorkingDirectory("/SSL");

        int reply = ftp.getReplyCode();
        System.out.println("Received Reply from FTP Connection:" + reply);

        if (FTPReply.isPositiveCompletion(reply)) {
            System.out.println("Connected Success");
        }
        System.out.println(f.getName().toString());

        File f1 = new File(location);
        in = new FileInputStream(f1);

        FileInputStream input = new FileInputStream(f1);
        // ftp.storeFile(f.getName().toString(),in);

        //ProgressMonitorInputStream is= new ProgressMonitorInputStream(getParent(), "st", in);
        OutputStream ftpOut = ftp.storeFileStream(f.getName().toString());


        System.out.println(ftpOut.toString());
        //newname hereSystem.out.println(ftp.remoteRetrieve(f.toString()));
        OutputStream output = new BufferedOutputStream(ftpOut);
        CopyStreamListener listener = new CopyStreamListener() {
            public void bytesTransferred(final long totalBytesTransferred, final int bytesTransferred, final long streamSize) {

                setProgress((int) Math.round(((double) totalBytesTransferred / (double) streamSize) * 100d));

            }

            @Override
            public void bytesTransferred(CopyStreamEvent arg0) {
                // TODO Auto-generated method stub
            }
        };

        Util.copyStream(input, output, ftp.getBufferSize(), f.length(), listener);

        return null;

    }
}

In your ActionListener of o (??) replace the thread execution code with

try {
    MyWorker worker = new MyWorker(new URL("http://localhost"), file);
    worker.addPropertyChangeListener(new PropertyChangeListener() {

        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            if (evt.getPropertyName().equals("progress")) {
                Integer progress = (Integer) evt.getNewValue();
                progressBar.setValue(progress);
            }
        }
    });
    worker.execute();
} catch (MalformedURLException ex) {
    ex.printStackTrace();
}

Note. You are ignoring the URL you pass to the constructor. http:// is not ftp:// so I doubt this will work...

这篇关于显示了在Java小程序的FTP上传文件时进度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆