服务端客户端的文件流式传输
在研究webservice的时候,发现文件流式的传输是基于socket的传输。
大致的流程是:
服务端客户端的通信->针对内容进行Stream的读取,并将数据放到buffer中->处理通信请求
另一接收端:针对传输过来的内容进行读取,用一个新的byte数组将内容存入。
下面是针对这一环节对文件流式处理展示,不包含通信过程。
客户端:
/**
* 取出单个文件,并以文件流的形式向服务端传送内容
* @param Filename 文件名称,不包前缀
* @param path 文件的具体地址
*/
public void sendSingleFile(String Filename,String path) {
try {
File file = null;
File files = new File(path);
File[] fs = files.listFiles();
for (int i = 0; i < fs.length; i++) {
if (fs[i].getName().endsWith(Filename + ".xml")) {//设置需要取的文件,也可以用正则来设置
String singleFile = fs[i].getAbsolutePath(); //取到单个文件的路径
file = new File(singleFile);
if (file.isFile() && file.exists()) {
InputStreamReader read = new InputStreamReader(new FileInputStream(file), "utf-8");//用FileReader 不可以指定编码,所以不用FileReader了。
BufferedReader br = new BufferedReader(read);
String lineText = new String();
StringBuilder strBuf = new StringBuilder();
SimpleDateFormat sf = new SimpleDateFormat("_yyyyMMdd_hhmmss"); //服务器获取文件后能看到文件接收的具体时间是什么时候生成的
String pdate = sf.format(new Date());
while ((lineText = br.readLine()) != null) {
strBuf.append(lineText);
}
String[] addTimeFile = file.getName().split("\\.");
System.out.println(strBuf + " " + addTimeFile[0] + pdate + "." + addTimeFile[1]);
// Socket文件流式传输
// service.getValue(strBuf + "\n\r", addTimeFile[0] + pdate + "." + addTimeFile[1]); //服务器接收的内容,服务器发送经过处理后的文件名
} else {
System.out.println("找不到指定的文件");
}
}
}
} catch (Exception e) {
System.out.println("读取文件内容出错");
e.printStackTrace();
}
}
服务端:
/**
*
* @param fileContent
* @param fileName
*/
public void getValue(String fileContent, String fileName) {
try {
String filePaths = "D:\\xxxx\\" + fileName;
int temp = this.writeFile(filePaths, fileContent.getBytes("utf-8")); //使用指定的字符集将字符串编码为 byte 序列,并将结果存储到一个新的 byte 数组中。
if (temp >= 0) {
System.out.println("写入文件成功!");
} else {
System.out.println("写入文件失败!");
}
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
}
/**
* 服务器的流式传输-服务器端接收后输出
* @param filePaths
* @param content
* @return
*/
private int writeFile(String filePaths, byte[] content) {
System.out.println("开始写入文件....");
FileOutputStream os = null;
try {
os = new FileOutputStream(filePaths, true);
os.write(content);
os.flush();
} catch (Exception e) {
return -1;
} finally {
try {
if (null != os) {
os.close();
}
} catch (IOException E) {
}
}
System.out.println("写入文件成功");
os = null;
return 0;
}
版权声明:本文为x_bessie原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。