如何使用Java通过网络将文件从一台计算机传输到另一台计算机? [英] How to transfer files from one computer to another over the network using Java?

查看:893
本文介绍了如何使用Java通过网络将文件从一台计算机传输到另一台计算机?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个简单的应用程序,最好是跨平台的应用程序,它可以在两台计算机之间发送文件。

I need a simple application, preferably a cross-platform one, that enables sending of files between two computers.

它只需要接受并发送文件,并显示进度条。我可以使用哪些应用程序或如何编写应用程序?

It just need to accept and send the files, and show a progress bar. What applications could I use or how could I write one?

推荐答案

发送和接收文件

发送和接收文件基本上分为两段简单的代码。

The sending and receiving of a file basically breaks down to two simple pieces of code.

接收代码:

ServerSocket serverSoc = new ServerSocket(LISTENING_PORT);

Socket connection = serverSoc.accept();

// code to read from connection.getInputStream();

发送代码:

File fileToSend;
InputStream fileStream = new BufferedInputStream(fileToSend);

Socket connection = new Socket(CONNECTION_ADDRESS, LISTENING_PORT);
OutputStream out = connection.getOutputStream();

// my method to move data from the file inputstream to the output stream of the socket
copyStream(fileStream, out);

发送代码的代码将在他们想要发送代码的计算机上运行一个文件。

The sending piece of code will be ran on the computer that is sending the code when they want to send a file.

接收代码需要放在循环中,这样每当有人想要连接到服务器时,服务器就可以处理请求然后返回等待serverSoc.accept()。

The receiving code needs to be put inside a loop, so that everytime someone wants to connect to the server, the server can handle the request and then go back to waiting on serverSoc.accept().

为了允许在两台计算机之间发送文件,每台计算机都需要运行服务器(接收代码)来监听传入的文件,当他们想要发送文件时,他们都需要运行发送代码。

To allow sending files between both computers, each computer will need to run the server (receiving code) to listen for incoming files, and they will both need to run the sending code when they want to send a file.

进度条

Swing中的 JProgressBar 很容易使用。但是,让它正常工作并显示文件传输的当前进度稍微困难一些。

The JProgressBar in Swing is easy enough to use. However, getting it to work properly and show current progress of the file transfer is slightly more difficult.

要获得显示在表单上的进度条,只需删除它到 JFrame 并设置 setIndeterminate(false)这样就可以显示你的程序正在运行。

To get a progress bar to show up on a form only involves dropping it onto a JFrame and perhaps setting setIndeterminate(false) so hat it shows that your program is working.

要正确实现进度条,您需要创建自己的 SwingWorker 。 Java教程在他们的并发课程中有一个很好的例子。

To implement a progress bar correctly you will need to create your own implementation of a SwingWorker. The Java tutorials have a good example of this in theirlesson in concurrency.

这是一个相当困难的问题。如果您需要更多帮助,我建议您自己提出这个问题。

This is a fairly difficult issue on its's own though. I would recommend asking this in it's own question if you need more help with it.

这篇关于如何使用Java通过网络将文件从一台计算机传输到另一台计算机?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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