我在编程(Java网络编程和io流)中使用该功能时就是下载时会出现下载大小不对的情况(望解决),如下图
第二个文件是我下载下来的,第一个是我复制过来的他们两大小明显不同但文章的开头和结尾却传入成功
开头
结束
/**
* 客户端代码
*/
else if (info.equals("3")) {
//下载之前先要做查询
//这个map的key代表一个数字序号,value代表书名
Map<String, String> bookMap = bookClientService.queryPrintAllBook(dataUtil);
System.out.println("请选择下面显示的小说名字进行下载");
//遍历存放小说的map
for (Map.Entry<String, String> entry : bookMap.entrySet()) {
System.out.println(entry.getKey() + "." + entry.getValue());
}
System.out.println("请输入小说序号:--------------");
String bookName = sc.next();
//输入的序号与map的key对比是否存在
if (!bookMap.containsKey(bookName)){
System.out.println("【温馨提示】没有该序号的小说");
System.out.println("----请输入已有的小说序号----");
}
//存在时得到对value及书名
String bookNames = bookMap.get(bookName);//收集到用户输入的小说名字
//这是我将客户端的操作封装为一个对象
MessageEntity messageEntity = new MessageEntity();
//代表服务端将进行操作4
messageEntity.setOprator(4);
messageEntity.setBookName(bookNames);
dataUtil.sendData(messageEntity);//用于处理数据
//Contain.downloadPath是一个给定的常量(默认下载路径)
File file = new File(Contain.downloadPath + "\\" + bookNames);
if (!file.exists()) {//该文件不存在时创建
file.createNewFile();
}else {
file.delete();
file.createNewFile();
}
while (true) {
String downLoadContent = dataUtil.receiveData();
if (downLoadContent.endsWith("end")) {//当读到end时表示传完了
System.out.println("-----下载完成!----");
FileOutputStream fos = new FileOutputStream(file, true);
fos.write(downLoadContent.replaceAll("end","").getBytes());
break;
}
//续写操作
FileOutputStream fos = new FileOutputStream(file, true);
fos.write(downLoadContent.getBytes());
}
String s = ct.menu();
postBookResult(s);
}
/**
* 服务端代码
*/
else if(m.getOprator()==4){//下载
//获取现需要下载的小说的名字
String bookName = m.getBookName();
String downLoadPath = Contain.bookPath+"\\"+ bookName;
File downLoadFile = new File(downLoadPath);
FileInputStream fis = new FileInputStream(downLoadFile);
DecimalFormat df = new DecimalFormat("#.0");
int total =0;
while ((total = fis.read(bs))!=-1){
String message = new String(bs,0,total);
os.write(message.getBytes());
}
//读完了
os.write("end".getBytes());
}
/**
*DataUtil 类
*/
public class DataUtil {
static char[] chars =new char[1000];
Socket socket;
ObjectOutputStream oos = null;
public DataUtil(Socket socket){
this.socket=socket;
}
public void sendData(MessageEntity messageEntity) throws IOException {
OutputStream os = socket.getOutputStream();
if(oos==null){
oos= new ObjectOutputStream(os);
}
//写到服务器
oos.writeObject(messageEntity);
}
//接受数据
public String receiveData() throws IOException {
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
int total = isr.read(chars);
//把服务器相应的消息 判断一下
String result = new String(chars,0,total);
return result;
}
}