1
显示下载进度我正在通过TCP连接发送一个mp3文件的程序。我正在尝试使用JProgressBar来显示下载进度。但是,在完全下载文件之前,我不知道文件大小。无论如何,我可以在从服务器端下载文件之前获取文件大小?通过TCP连接传输mp3文件。使用JProgressBar
在此先感谢。这里是我的代码
SERVER:
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
dataOut = new BufferedOutputStream(clientSocket.getOutputStream());
file = new File(LIBRARY, data);
//get length of file
int fileLength = (int)file.length();
fileData = new byte[fileLength];
fileIn = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fileIn);
bis.read(fileData, 0 , fileData.length);
OutputStream os = clientSocket.getOutputStream();
os.write(fileData, 0 , fileData.length);
os.flush();
clientSocket.close();
客户:
int filesize=999999999; //A TEMPORARY FILE SIZE
long start = System.currentTimeMillis();
int bytesRead;
int current = 0;
// localhost for testing
Socket sock = new Socket(SERVER_NAME,DEST_PORT);
PrintWriter out = new PrintWriter(sock.getOutputStream(), true);
// receive file
byte [] mybytearray = new byte [filesize];
out.println(request);
InputStream is = sock.getInputStream();
FileOutputStream fos = new FileOutputStream(request);
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;
System.out.println(bytesRead);
do {
bytesRead = is.read(mybytearray, current, (mybytearray.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);
bos.write(mybytearray, 0 , current);
bos.flush();
long end = System.currentTimeMillis();
System.out.println(current);
bos.close();
sock.close();
编辑您的问题,包括 “解决” 解决的办法是不StackOverflow的是如何工作的。请阅读[帮助]页面,特别是[我可以回答我自己的问题?](http://stackoverflow.com/help/self-answer)部分。 –
谢谢。修正了它... – pininfarina
谢谢。这好多了。 (你甚至可以在几个小时内接受它是正确的,但是你不会因为这样做而获得声望)。 –