Posted on 2009-09-10 20:34
love1563 閱讀(1004)
評論(0) 編輯 收藏
/**
* 發送端
*/
class Client {
// 網上抄來的,將 int 轉成字節
public static byte[] i2b(int i) {
return new byte[]{
(byte) ((i >> 24) & 0xFF),
(byte) ((i >> 16) & 0xFF),
(byte) ((i >> 8) & 0xFF),
(byte) (i & 0xFF)
};
}
/**
* 發送文件。文件大小不能大于 {@link Integer#MAX_VALUE}
*
* @param hostname 接收端主機名或 IP 地址
* @param port 接收端端口號
* @param filepath 文件路徑
*
* @throws IOException 如果讀取文件或發送失敗
*/
public void sendFile(String hostname, int port, String filepath) throws IOException {
File file = new File(filepath);
FileInputStream is = new FileInputStream(filepath);
Socket socket = new Socket(hostname, port);
OutputStream os = socket.getOutputStream();
try {
int length = (int) file.length();
System.out.println("發送文件:" + file.getName() + ",長度:" + length);
// 發送文件名和文件內容
writeFileName(file, os);
writeFileContent(is, os, length);
} finally {
os.close();
is.close();
}
}
// 輸出文件內容
private void writeFileContent(InputStream is, OutputStream os, int length) throws IOException {
// 輸出文件長度
os.write(i2b(length));
// 輸出文件內容
byte[] buffer = new byte[4096];
int size;
while ((size = is.read(buffer)) != -1) {
os.write(buffer, 0, size);
}
}
// 輸出文件名
private void writeFileName(File file, OutputStream os) throws IOException {
byte[] fn_bytes = file.getName().getBytes();
os.write(i2b(fn_bytes.length)); // 輸出文件名長度
os.write(fn_bytes); // 輸出文件名
}
}
本文來自: IT知道網(http://www.itwis.com) 詳細出處參考:http://www.itwis.com/html/java/j2se/20090304/3503_2.html