一、读取文件为字节
String reqFile = "F:\\ZX\\work\\testol.pdf";
public static byte[] read4file(String filename) throws Exception {
FileInputStream fis = null;
ByteArrayOutputStream baos = null;
try {
fis = new FileInputStream(filename);
baos = new ByteArrayOutputStream();
byte[] bytes = new byte[128];
boolean var4 = false;
int n;
while((n = fis.read(bytes)) > 0) {
baos.write(bytes, 0, n);
}
} finally {
try {
if (fis != null) {
fis.close();
}
if (baos != null) {
baos.close();
}
} catch (Exception var10) {
}
}
return baos.toByteArray();
}
二 socket读取InputStream
方式一 读取为 字符
public static byte[] send(byte[] signByte,String url,Integer port) {
Socket socket = null;
OutputStream outputStream = null;
InputStream inputStream = null;
//BufferedReader br = null;
String info=null;
try {
//建立TCP连接
socket = new Socket(url, port);
logger.info("创建连接成功");
//写入数据
outputStream = socket.getOutputStream();
outputStream.write(signByte);
logger.info("发送数据结束");
//获取响应
inputStream = socket.getInputStream();
br = new BufferedReader(new InputStreamReader(inputStream));
while((info=br.readLine())!=null){
logger.info(info);
}
// br.close();
} catch (UnknownHostException e1) {
logger.info("创建连接失败");
} catch (IOException e1) {
logger.info("发送数据失败");
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
outputStream.close();
socket.close();
logger.info("断开连接");
} catch (Exception var10) {
}
}
return baos.toByteArray();
}
二 读取inputStream为字节流
public static byte[] send(byte[] signByte,String url,Integer port) {
Socket socket = null;
OutputStream outputStream = null;
InputStream inputStream = null;
//BufferedReader br = null;
String info=null;
ByteArrayOutputStream baos = null;
try {
//建立TCP连接
socket = new Socket(url, port);
logger.info("创建连接成功");
//写入数据
outputStream = socket.getOutputStream();
outputStream.write(signByte);
logger.info("发送数据结束");
//获取响应
inputStream = socket.getInputStream();
baos = new ByteArrayOutputStream();
byte[] bytes = new byte[128];
int n;
while((n = inputStream.read(bytes)) > 0) {
baos.write(bytes, 0, n);
}
} catch (UnknownHostException e1) {
logger.info("创建连接失败");
} catch (IOException e1) {
logger.info("发送数据失败");
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
if (baos != null) {
baos.close();
}
outputStream.close();
socket.close();
logger.info("断开连接");
} catch (Exception var10) {
}
}
return baos.toByteArray();
}
本文详细介绍了如何使用Java读取本地文件为字节流,以及通过Socket进行数据发送和接收的方法。包括了利用FileInputStream和ByteArrayOutputStream读取文件,和通过Socket建立TCP连接,发送及接收字节流数据的具体实现。

3406

被折叠的 条评论
为什么被折叠?



