java实现socket_Java实现Socket发送和接收文件的代码

该博客介绍了如何使用Java实现通过网络发送文件。首先,它提供了一个将整数转换为字节的方法,然后创建一个Socket连接到指定的主机和端口。接着,它打开文件并逐块读取,同时发送文件名和长度信息,最后发送文件内容。
摘要由CSDN通过智能技术生成

/**

* 发送端

*/

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值