zoukankan      html  css  js  c++  java
  • Java逻辑分页代码

    前台jsp代码如下:

    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title>office模版管理</title>
    <%@include file="/commons/include/manageCommon.jsp"%>
    <link rel="stylesheet" href="${ctx}/assets/stylesheets/thestyle.css" />
    <script type="text/javascript">
        
        function showOffice(officeName,officeExt,hideOfficePath){
            window.location.href="${ctx}/platform/system/sysOffice/download.ht?officeName="+officeName+"&officeExt="+officeExt+"&hideOfficePath="+hideOfficePath;
        }
        
        function editOffice(officePath,officeExt){
            if(officeExt != "doc" && officeExt != "DOC" && officeExt != "docx" && officeExt != "DOCX"){
                layer.msg("请选择doc或docx格式的文书进行编辑!", {
                    time: 2000,
                    type: 1,
                    skin: "layer-tips-box",
                    anim: 1,
                    offset: "30%",
                    content: content1.replace("#tips#", "请选择doc或docx格式的文书进行编辑!")
                });
                return false;
            }
            window.location.href = "edit.ht?officePath="+officePath;    
        }
        
        function changePageSize(){
            var pageSize = $("#pageSizeSelect option:selected").val();
            $("#pageSizeSpan").html(pageSize);
            $("#pageSize").val(pageSize);
            var currentPage = $("#currentPageInput").val();
            $("#currentPage").val(currentPage);
            $("#searchForm").submit();
        }
        
        function first(){
            $("#currentPage").val(parseInt(1));
            $("#currentPageInput").val(parseInt(1));
            $("#searchForm").submit();
        }
        
        function previous(){
            var currentPage = $("#currentPageInput").val();
            if(parseInt(currentPage)-1 >= parseInt(1)){
                $("#currentPage").val(parseInt(currentPage)-1);
                $("#currentPageInput").val(parseInt(currentPage)-1);
            }
            $("#searchForm").submit();
        }
        
        function next(){
            var currentPage = $("#currentPageInput").val();
            if(parseInt(currentPage)+1 <= parseInt("${totalPage}")){
                $("#currentPage").val(parseInt(currentPage)+1);
                $("#currentPageInput").val(parseInt(currentPage)+1);
            }
            $("#searchForm").submit();
        }
        
        function last(){
            $("#currentPage").val(parseInt("${totalPage}"));
            $("#currentPageInput").val(parseInt("${totalPage}"));
            $("#searchForm").submit();
        }
        
        function jumpTo(){
            var currentPage = $("#currentPageInput").val();
            $("#currentPage").val(parseInt(currentPage));
            $("#searchForm").submit();
        }
    </script>
    </head>
    <body>
        <div class="panel">    
            <div class="panel-heading">
                <form id="searchForm" method="post" action="list.ht" class="form-inline inputFrom">
                    <div class="form-group">
                        <span>文书名称:</span> <input type="text" name="officeName"
                            class="form-control input-sm" value="${officeName}" />
                    </div>
                    <input id="pageSize" name="pageSize" value="${pageSize }" style="display:none"/>
                    <input id="currentPage" name="currentPage" value="${currentPage }" style="display:none"/>
                </form>
            </div> 
            <div class="panel-body">
                <c:set var="checkAll">
                    <input type="checkbox" id="chkall"/>
                </c:set>
                <display:table name="sysOfficeList" id="sysOfficeItem" requestURI="list.ht" sort="external" cellpadding="1" cellspacing="1"
                    class="table-grid table table-bordered table-striped table-hover text-center">
                    
                    <display:caption>                
                        <div class="btn-group-p">                    
                            <a class="btn btn-primary link search" id="btnSearch">
                                <span class="fa fa-search">查询</span>
                            </a>                    
                            <a class="btn btn-primary" href="add.ht">
                                <span class="fa fa-plus">添加</span>
                            </a>
                            <a class="btn btn-primary link del" action="del.ht">
                                <span class="fa fa-times">批量删除</span>
                            </a>
                        </div>
                    </display:caption>
                    
                    <display:column title="${checkAll}" media="html" style="30px;">
                        <input type="checkbox" class="pk" name="officePath" value="${sysOfficeItem.officePath}">
                    </display:column>
                    <display:column title="文书名称" class="text-left">
                    <%-- <a class="titleTip"  title="${sysOfficeItem.officeName}" href="javascript:void(0)" onclick="showOffice('${sysOfficeItem.officeName}','${sysOfficeItem.officeExt}','${sysOfficeItem.hideOfficePath}')"> --%>    
                    <a class="titleTip"  title="${sysOfficeItem.officeName}" href="get.ht?officePath=${sysOfficeItem.officePath}">                 
                          ${fn:substring(sysOfficeItem.officeName,0,10)}${fn:length(sysOfficeItem.officeName)>10?'...':''}
                    </a>
                    </display:column>
                    <display:column title="文书后缀">
                        ${sysOfficeItem.officeExt}
                    </display:column>
                    <display:column title="文书路径">
                        <span class="titleTip"  title="${sysOfficeItem.officePath}">
                            ${fn:substring(sysOfficeItem.officePath,0,80)}${fn:length(sysOfficeItem.officePath)>80?'...':''}
                        </span>
                    </display:column>
                    <display:column title="管理" media="html"  class="row-nowrap text-center">
                        <a href="get.ht?officePath=${sysOfficeItem.officePath}" class="link detail gray leave-blank">明细</a>
                        <a onclick="editOffice('${sysOfficeItem.officePath}','${sysOfficeItem.officeExt}')" href="javascript:void(0)" class="link edit gray leave-blank">编辑</a>
                        <a href="del.ht?officePath=${sysOfficeItem.officePath}" class="link del gray leave-blank">删除</a>
                    </display:column>
                </display:table>
                <div class="btn-group" style="background-color: white; 100%">
                    <div style="float: left;">
                        <span>每页记录</span>
                        <select id="pageSizeSelect" name="pageSizeSelect" onchange="changePageSize()" class="input-sm" style="margin: 0 5px;">
                            <option value="5" <c:out value="${pageSize eq '5'? 'selected' : '' }"/>>5</option>
                            <option value="10" <c:out value="${pageSize eq '10'? 'selected' : '' }"/>>10</option>
                            <option value="15" <c:out value="${pageSize eq '15'? 'selected' : '' }"/>>15</option>
                            <option value="20" <c:out value="${pageSize eq '20'? 'selected' : '' }"/>>20</option>
                            <option value="50" <c:out value="${pageSize eq '50'? 'selected' : '' }"/>>50</option>
                            <option value="100" <c:out value="${pageSize eq '100'? 'selected' : '' }"/>>100</option>
                        </select>
                        <a href="javascript:window.location.reload()"><span class="fa fa-refresh" style="display: inline-block;margin:0 5px;"></span></a>
                        <span style="display: inline-block;margin:0 5px;">显示记录从1到<span id="pageSizeSpan" name="pageSizeSpan">10</span>,总数 ${totalNum }条</span>
                        <a href="javascript:;" onclick="first()" title="首页"><span class="fa fa-step-backward" style="display: inline-block;margin:0 5px;"></span></a>
                        <a href="javascript:;" onclick="previous();" title="上一页" ><span class="fa fa-chevron-left"></span></a>
                        <span style="display: inline-block;margin:0 5px;">
                            <input class="pageInputText" size="4" value="${currentPage}" maxlength="4" type="text" id="currentPageInput" name="currentPageInput" style=" 35px;border: 1px solid #ddd;height: 24px;line-height: 24px;">/<span style="margin-left:4px;">${totalPage }</span>
                        </span>
                        <a href="javascript:;" onclick="next()" title="下一页" ><span class="fa fa-chevron-right" style="display: inline-block;margin:0 5px;"></span></a>
                        <a href="javascript:;" onclick="last()" title="尾页" ><span class="fa fa-step-forward" style="display: inline-block;margin:0 5px;"></span></a>
                        <input type="button" id="btnGo" value="GO" onclick="jumpTo();" class="btn btn-primary">
                        <div class="l-clear"></div>
                    </div>
                </div>
            </div><!-- end of panel-body -->                
        <!-- end of panel -->
    </body>
    <!-- 提示 -->
    <link rel="stylesheet" type="text/css" href="${ctx}/js/poshytip-1.2/tip-yellowsimple/tip-yellowsimple.css" />
    <script type="text/javascript" src="${ctx}/js/poshytip-1.2/jquery.poshytip.js"></script>
    <script type="text/javascript" src="${ctx}/js/util/toolTipCommon.js"></script>
    </html>

    后台Java代码如下:

    package com.ksource.platform.controller.system;
    
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.io.PrintWriter;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.net.URLEncoder;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Map;
    import javax.annotation.Resource;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import com.ksource.platform.model.system.SysAuditModelType;
    import com.ksource.platform.model.system.SysFile;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.multipart.MultipartFile;
    import org.springframework.web.multipart.MultipartHttpServletRequest;
    import org.springframework.web.servlet.ModelAndView;
    import com.ksource.core.annotion.Action;
    import com.ksource.core.annotion.ActionExecOrder;
    import com.ksource.core.util.AppConfigUtil;
    import com.ksource.core.util.FileUtil;
    import com.ksource.core.web.ResultMessage;
    import com.ksource.core.web.controller.BaseController;
    import com.ksource.core.web.query.QueryFilter;
    import com.ksource.core.web.util.RequestUtil;
    import com.ksource.platform.service.system.SysFileService;
    import com.ksource.pwlp.controller.system.SysOffice;
    
    @Controller
    @RequestMapping({ "/platform/system/sysOffice/" })
    @Action(ownermodel = SysAuditModelType.BASICDATA_MANAGEMENT)
    public class SysOfficeController extends BaseController {
    
        @Resource
        private SysFileService sysFileService;
        
        /**
         * 查看系统文书模版分页列表
         * @param request
         * @return
         * @throws Exception
         */
        @RequestMapping({ "list" })
        @Action(description = "查看系统文书模版分页列表", detail = "查看系统文书模版分页列表")
        public ModelAndView list(HttpServletRequest request) throws Exception {
            QueryFilter filter = new QueryFilter(request, "sysOfficeItem");
            String officePath = request.getSession().getServletContext().getRealPath("/")+"WEB-INF/fileTemplate/office";
            List<SysOffice> sysOfficeList = new ArrayList<SysOffice>();
            findFileList(new File(officePath),sysOfficeList,filter);
            //pageSize 每页展示个数
            int pageSize = RequestUtil.getInt(request, "pageSize",10); 
            //currentPage 当前页
            int currentPage = RequestUtil.getInt(request, "currentPage",1); 
            //totalNum 总数
            int totalNum = sysOfficeList.size();
            //totalPage 总页数
            int totalPage = 0;
            if(sysOfficeList.size() % pageSize==0){
                //说明整除,正好每页显示pageSize条数据,没有多余一页要显示少于pageSize条数据的
                totalPage = sysOfficeList.size() / pageSize;
            }else{
                //不整除,就要在加一页,来显示多余的数据。
                totalPage = sysOfficeList.size() / pageSize + 1;
            }
            List<SysOffice> officeList = new ArrayList<SysOffice>();
            for (int i = (currentPage-1)*pageSize; i < currentPage*pageSize; i++) {
                if(i < totalNum){
                    officeList.add(sysOfficeList.get(i));
                }
            }
            ModelAndView mv = getAutoView().addObject("sysOfficeList", officeList).addObject("pageSize", pageSize).addObject("currentPage", currentPage).addObject("totalNum", totalNum).addObject("totalPage", totalPage);
            Object obj = filter.getFilters().get("officeName");
            if(obj != null){
                String officeName = obj.toString();
                mv.addObject("officeName", officeName);
            }
            return mv;
        }
    
        /**
         * 查看系统文书模版明细
         * @param request
         * @return
         * @throws Exception
         */
        @RequestMapping({ "get" })
        @Action(description = "查看系统文书模版明细", detail = "查看系统文书模版明细")
        public ModelAndView get(HttpServletRequest request) throws Exception {
            String officePath = RequestUtil.getString(request, "officePath");
            SysOffice sysOffice = new SysOffice();
            File file = new File(officePath);
            if(file != null){
                String officeName = file.getName().substring(0, file.getName().lastIndexOf("."));
                sysOffice.setOfficeName(officeName);
                String officeExt = file.getName().substring(file.getName().lastIndexOf(".")+1, file.getName().length());
                sysOffice.setOfficeExt(officeExt);
                sysOffice.setOfficePath(officePath);
                sysOffice.setHideOfficePath(sysOffice.getOfficePath().replace("\", "//"));
            }
            return getAutoView().addObject("sysOffice", sysOffice);
        }
        
        /**
         * 编辑文书模板页面
         * @param response
         * @param request
         * @return
         * @throws Exception
         */
        @RequestMapping("/add")
        @Action(description = "编辑文书模板页面", detail = "编辑文书模板页面")
        public ModelAndView add(HttpServletResponse response, HttpServletRequest request) throws Exception {
            String officePath = RequestUtil.getString(request, "officePath", "");
            SysOffice sysOffice = new SysOffice();
            if(!"".equals(officePath)){
                File file = new File(officePath);
                if(file != null){
                    String officeName = file.getName().substring(0, file.getName().lastIndexOf("."));
                    sysOffice.setOfficeName(officeName);
                    String officeExt = file.getName().substring(file.getName().lastIndexOf(".")+1, file.getName().length());
                    sysOffice.setOfficeExt(officeExt);
                    sysOffice.setOfficePath(officePath);
                    sysOffice.setHideOfficePath(sysOffice.getOfficePath().replace("\", "//"));
                }
            }
            ModelAndView mv = this.getAutoView();
            return mv.addObject("sysOffice", sysOffice);
        }
        
        /**
         * 编辑文书模板页面
         * @param response
         * @param request
         * @return
         * @throws Exception
         */
        @RequestMapping("/edit")
        @Action(description = "编辑文书模板页面", detail = "编辑文书模板页面")
        public ModelAndView edit(HttpServletResponse response, HttpServletRequest request) throws Exception {
            String officePath = RequestUtil.getString(request, "officePath", "");
            SysOffice sysOffice = new SysOffice();
            if(!"".equals(officePath)){
                File file = new File(officePath);
                if(file != null){
                    String officeName = file.getName().substring(0, file.getName().lastIndexOf("."));
                    sysOffice.setOfficeName(officeName);
                    String officeExt = file.getName().substring(file.getName().lastIndexOf(".")+1, file.getName().length());
                    sysOffice.setOfficeExt(officeExt);
                    sysOffice.setOfficePath(officePath);
                    sysOffice.setHideOfficePath(sysOffice.getOfficePath().replace("\", "//"));
                }
            }
            ModelAndView mv = this.getAutoView();
            return mv.addObject("sysOffice", sysOffice);
        }
        
        /**
         * 加载文书模板
         * @param response
         * @param request
         * @return
         * @throws Exception
         */
        @RequestMapping("/editTemplate")
        public ModelAndView editTemplate(HttpServletResponse response, HttpServletRequest request) throws Exception {
            String hideOfficePath = RequestUtil.getString(request, "hideOfficePath");
            ModelAndView mv = this.getAutoView();
            if(!"".equals(hideOfficePath)){
                File file = new File(hideOfficePath.replace("//", "\"));
                if(file != null){
                    String officeName = file.getName().substring(0, file.getName().lastIndexOf("."));
                    String officeExt = file.getName().substring(file.getName().lastIndexOf(".")+1, file.getName().length());
                    mv.addObject("officeName", officeName);
                    mv.addObject("officeExt", officeExt);
                }
            }
            mv.addObject("hideOfficePath", hideOfficePath);
            return mv;
        }
        
        /**
         * 获取文书模板 
         * @param request
         * @param response
         * @throws Exception
         */
        @RequestMapping("getTemplate")
        @Action(description = "获取文书模板", detail = "获取文书模板")
        public void getTemplate(HttpServletRequest request, HttpServletResponse response) throws Exception {
            String hideOfficePath = RequestUtil.getString(request, "hideOfficePath");
            hideOfficePath = java.net.URLDecoder.decode(hideOfficePath , "UTF-8");
            hideOfficePath = hideOfficePath.replace("/", "\");
            byte[] readByte = FileUtil.readByte(hideOfficePath);
            try {
                response.getOutputStream().write(readByte);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
        @RequestMapping({ "saveOffice" })
        @Action(description = "保存文书模板", execOrder = ActionExecOrder.AFTER)
        public void saveFile(MultipartHttpServletRequest request, HttpServletResponse response) throws Exception {
            String hideOfficePath = RequestUtil.getString(request, "hideOfficePath");
            PrintWriter writer = response.getWriter();
            try {
                Map files = request.getFileMap();
                Iterator it = files.values().iterator();
                while (it.hasNext()) {
                    MultipartFile f = (MultipartFile) it.next();
                    File file = new File(hideOfficePath);
                    if (file.exists()) {
                        file.delete();
                    }
                    FileUtil.writeByte(hideOfficePath, f.getBytes());
                    writeResultMessage(writer, "保存文书模板成功!", ResultMessage.Success);
                }
            } catch (Exception e) {
                    writeResultMessage(writer, "保存文书模板失败!", ResultMessage.Fail);
            }
        }
        
        /**
         * 删除系统文书模版
         * @param request
         * @param response
         * @throws Exception
         */
        @RequestMapping({ "del" })
        @Action(description = "删除系统文书模版", execOrder = ActionExecOrder.BEFORE, detail = "删除系统文书模版:<#list StringUtils.split(id,",") as item><#assign entity=sysOfficeTemplateService.getById(Long.valueOf(item))/>【${entity.subject}】</#list>")
        public void del(HttpServletRequest request, HttpServletResponse response) throws Exception {
            String preUrl = RequestUtil.getPrePage(request);
            ResultMessage message;
            try {
                String[] officePath = RequestUtil.getStringAryByStr(request, "officePath");
                for (int i = 0; i < officePath.length; i++) {
                    File file = new File(officePath[i]);
                    if (file.isFile()) {
                        file.delete();
                    }
                }
                message = new ResultMessage(1, "删除文书成功!");
            } catch (Exception ex) {
                message = new ResultMessage(0, "删除文书失败:" + ex.getMessage());
            }
            addMessage(message, request);
            response.sendRedirect(preUrl);
        }
        
        /**
         * 文件下载
         * 
         * @Description:
         * @param fileName
         * @param request
         * @param response
         * @return
         * @throws Exception
         */
        @RequestMapping("/download")
        public String downloadFile(HttpServletRequest request,
                HttpServletResponse response) throws Exception {
            String officeName = RequestUtil.getString(request, "officeName");
            officeName = java.net.URLDecoder.decode(officeName , "UTF-8");
            String officeExt = RequestUtil.getString(request, "officeExt");
            String fullOfficeName = officeName + "." + officeExt;
            fullOfficeName = fullOfficeName.replace(" ", "");
            fullOfficeName = URLEncoder.encode(fullOfficeName,"UTF-8");
            String hideOfficePath = RequestUtil.getString(request, "hideOfficePath");
            String officePath = hideOfficePath.replace("//", "\");
            if (officePath != null && !"".equals(officePath)) {
                File file = new File(officePath);
                if (file.exists()) {
                    response.setContentType("application/force-download");// 设置强制下载不打开
                    response.setHeader("Content-disposition","attachment; filename="+fullOfficeName);
                    byte[] buffer = new byte[1024];
                    FileInputStream fis = null;
                    BufferedInputStream bis = null;
                    try {
                        fis = new FileInputStream(file);
                        bis = new BufferedInputStream(fis);
                        OutputStream os = response.getOutputStream();
                        int i = bis.read(buffer);
                        while (i != -1) {
                            os.write(buffer, 0, i);
                            i = bis.read(buffer);
                        }
                    } catch (Exception e) {
                        // TODO: handle exception
                        e.printStackTrace();
                    } finally {
                        if (bis != null) {
                            try {
                                bis.close();
                            } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                        if (fis != null) {
                            try {
                                fis.close();
                            } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
            return null;
        }  
        
        /**
         * 上传文书到指定目录
         * @param request
         * @param response
         * @throws Exception
         */
        @RequestMapping({ "upload" })
        @ResponseBody
        @Action(description = "上传文书到指定目录")
        public Map upload(HttpServletRequest request, HttpServletResponse response) throws Exception {
            Long[] sysOfficeIds = RequestUtil.getLongAryByStr(request, "sysOfficeIds");
            Map map = new HashMap();
            for (int m = 0; m < sysOfficeIds.length; m++) {
                long fileId = sysOfficeIds[m];
                if (fileId == 0L) {
                    map.put("result", "fileIdIsZero");
                    return map;
                }
                SysFile sysFile = this.sysFileService.getById(Long.valueOf(fileId));
                if (sysFile == null) {
                    map.put("result", "fileNoExist");
                    return map;
                }
                String fileName = sysFile.getFileName() + "." + sysFile.getExt();
                String fileServicePath = AppConfigUtil.get("file_server_addr");
                String fullPath = "http://" + fileServicePath + File.separator + sysFile.getFilePath().replace("/", File.separator);
                fullPath = fullPath.replace("\", "/");
                String uploadlujing = request.getSession().getServletContext().getRealPath("/")+"WEB-INF/fileTemplate/office";
                saveUrlAs(fullPath, uploadlujing, fileName, "GET");   
            }
            map.put("result", "fileUploadEnd");
            return map;
        }
        
        public static void findFileList(File dir, List<SysOffice> sysOfficeList, QueryFilter queryFilter) {
            if (!dir.exists() || !dir.isDirectory()) {// 判断是否存在目录
                return;
            }
            String[] files = dir.list();// 读取目录下的所有目录文件信息
            for (int i = 0; i < files.length; i++) {// 循环,添加文件名或回调自身
                File file = new File(dir, files[i]);
                if (file.isFile()) {// 如果文件
                    SysOffice sysOffice = new SysOffice();
                    if(file.getName() != null){
                        String officeName = file.getName().substring(0, file.getName().lastIndexOf("."));
                        Object obj = queryFilter.getFilters().get("officeName");
                        if(obj != null){
                            String ofn = obj.toString();
                            if(!"".equals(ofn) && ofn != null){
                                if(!officeName.contains(ofn)){
                                    continue;
                                }
                            }
                        }
                        sysOffice.setOfficeName(officeName);
                        String officeExt = file.getName().substring(file.getName().lastIndexOf(".")+1, file.getName().length());
                        sysOffice.setOfficeExt(officeExt);
                    }
                    sysOffice.setOfficePath(dir + "\" + file.getName());
                    sysOffice.setHideOfficePath(sysOffice.getOfficePath().replace("\", "//"));
                    sysOfficeList.add(sysOffice);// 添加文件全路径名
                } else {// 如果是目录
                    findFileList(file, sysOfficeList, queryFilter);// 回调自身继续查询
                }
            }
        }
        
    
        public static File saveUrlAs(String url, String filePath, String fileName, String method) {
            // System.out.println("fileName---->"+filePath);
            // 创建不同的文件夹目录
            File file = new File(filePath);
            // 判断文件夹是否存在
            if (!file.exists()) {
                // 如果文件夹不存在,则创建新的的文件夹
                file.mkdirs();
            }
            FileOutputStream fileOut = null;
            HttpURLConnection conn = null;
            InputStream inputStream = null;
            try {
                // 建立链接
                URL httpUrl = new URL(url);
                conn = (HttpURLConnection) httpUrl.openConnection();
                // 以Post方式提交表单,默认get方式
                conn.setRequestMethod(method);
                conn.setDoInput(true);
                conn.setDoOutput(true);
                // post方式不能使用缓存
                conn.setUseCaches(false);
                // 连接指定的资源
                conn.connect();
                // 获取网络输入流
                inputStream = conn.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(inputStream);
                // 判断文件的保存路径后面是否以/结尾
                if (!filePath.endsWith("/")) {
                    filePath += "/";
    
                }
                // 写入到文件(注意文件保存路径的后面一定要加上文件的名称)
                fileOut = new FileOutputStream(filePath + fileName);
                BufferedOutputStream bos = new BufferedOutputStream(fileOut);
                byte[] buf = new byte[4096];
                int length = bis.read(buf);
                // 保存文件
                while (length != -1) {
                    bos.write(buf, 0, length);
                    length = bis.read(buf);
                }
                bos.close();
                bis.close();
                conn.disconnect();
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("抛出异常!!");
            }
            return file;
        }
    
    }
  • 相关阅读:
    Palindrome Linked List 解答
    Word Break II 解答
    Array vs Linked List
    Reverse Linked List II 解答
    Calculate Number Of Islands And Lakes 解答
    Sqrt(x) 解答
    Find Median from Data Stream 解答
    Majority Element II 解答
    Binary Search Tree DFS Template
    188. Best Time to Buy and Sell Stock IV
  • 原文地址:https://www.cnblogs.com/henuyuxiang/p/11608846.html
Copyright © 2011-2022 走看看