📄 filetransfer.java
字号:
package com.zlf.qqclient.filetransfer;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.swing.JTextPane;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.SimpleAttributeSet;
import com.zlf.qqclient.utils.Public;
import com.zlf.qqclient.utils.QQUtils;
/**
*
* 文件发送线程类
* @author zlf
*
*/
public class FileTransfer extends Thread {
private Socket socket;
private BufferedInputStream bis = null;
private BufferedOutputStream bos = null;
private InputStream is = null;
private long total = 0L;
private long size =0L;
private int rate=0;
private int port;
private String ip;
private JTextPane textContent;
private String tmpfilename;
/**
*
* 文件发送线程构造
* @param port
* @param ip
* @param textContent
*
*/
public FileTransfer(int port, String ip,JTextPane textContent,String tmpfilename){
this.port = port;
this.ip = ip;
this.textContent = textContent;
this.tmpfilename = tmpfilename;
}
/**
*
* 开始接收的准备
* @param fileName
* @return
*
*/
public boolean ready(String fileName){
try {
socket = new Socket(ip, port);
bis = new BufferedInputStream(socket.getInputStream());
bos = new BufferedOutputStream(socket.getOutputStream());
is = new FileInputStream(fileName);
total = is.available();
return true;
} catch (UnknownHostException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
*
* 启动线程
*
*/
public void service(){
byte[] buf = new byte[1024];
try {
int len = is.read(buf,1,buf.length-1);
while(len != -1){
size += len;
rate= (int) (size*100/total);
if(size == total){
buf[0] = (byte) -1.19;
}
buf[0] = (byte)rate;
Public.myprogressbar.setValue(rate);//设置进度条
Public.lblrate.setText(String.valueOf(rate)+"%");
bos.write(buf,0 , len+1);
bos.flush();
len = is.read(buf,1,buf.length-1);
}
Public.myprogressbar.setVisible(false);
AttributeSet set = new SimpleAttributeSet();
textContent.getDocument().insertString(
textContent.getDocument().getLength(),
QQUtils.getCurDate()+":"+"\n文件发送完毕\n", set);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadLocationException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
}
/**
*
* close()关socket,输入,输出流
*
*/
public void close(){
try {
if(bos != null){
bos.close();
bos = null;
}
if(bis != null){
bis.close();
bis = null;
}
if(is != null){
is.close();
is = null;
}
if(socket != null){
socket.close();
socket = null;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run() {
if(ready(tmpfilename)){
service();
close();
this.interrupt();
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -