项目中遇到的问题与解决方法——持续添加

来源:互联网 发布:iphone清理内存软件 编辑:程序博客网 时间:2024/05/17 00:50

问题解决之前不会,学习解决了之后怕忘记。

纯属为了方便自己回头看,学习那些曾经不会的。持续添加。

1.要导入Excel,但是获取到的数字是科学计数法,比如11001000获取到的是1.01+E7

 // 把科学计数转换成常规数字String s=control.getStrValue("CONTROL_TYPE_NAME");    //s是1.01+E7BigDecimal bd = new BigDecimal(s);   String bd1=bd.toPlainString();备注:最后发现既然是字符串类型的,为什么不把Excel的格式改成文本,改了发现好了,麻麻的

2、验证URL

if(!ip.matches("\\b((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\b")) {mb.setFalseWithMsg("ip地址格式不正确!");};

3、验证网址

String test="((https|http|ftp|rtsp|mms)?://)?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?(([0-9]{1,3}\\.){3}[0-9]{1,3}|([0-9a-z_!~*'()-]+\\.)*([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\\.[a-z]{2,6})(:[0-9]{1,4})?((/?)|(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)";if(!webServiceAddress.matches(test)) {    mb.setFalseWithMsg("webService地址格式不正确");}

4、将一些信息生成xml

public String getStr() {        return "<prop>\n\t<propname>whatName</propname>\n\t<propsign>whatSign</propsign>\n\t<propvalue>null</propvalue>\n</prop>\n";    }StringBuffer sb = new StringBuffer();        sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");        // 缓急程度        String newRapId = getStr().replace("whatName", "缓急程度");        newRapId = newRapId.replace("whatSign", "rapId");        if (rapId != null) {            newRapId = newRapId.replace("null", rapId);        }        sb.append(newRapId);        // 发文单位        String newCreateUserCompany = getStr().replace("whatName", "发文单位");        newCreateUserCompany = newCreateUserCompany.replace("whatSign", "createUserCompany");        if (createUserCompany != null) {            newCreateUserCompany = newCreateUserCompany.replace("null", createUserCompany);        }        sb.append(newCreateUserCompany);        // 接收单位        String newReceiveCompanyName = getStr().replace("whatName", "接收单位");        newReceiveCompanyName = newReceiveCompanyName.replace("whatSign", "receiveCompanyName");        if (receiveCompanyName != null) {            newReceiveCompanyName = newReceiveCompanyName.replace("null", receiveCompanyName);        }        sb.append(newReceiveCompanyName);        return sb.toString();public void writeXml(FileInfo fileInfo) {        try {            String xmlFile = parseListToString(fileInfo);            File filePath = new File("D:/OAFILE");            if (!filePath.exists()) {                filePath.mkdirs();            }            String target = "D:/OAFILE/" + fileInfo.getId() + ".xml";            FileWriter writer = new FileWriter(target);//这是第一种写法            //第二种写法:这种可以确定编码类型Writer writer=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(targetFile), "UTF-8"));            writer.write(xmlFile);            writer.flush();            writer.close();        } catch (IOException e) {            e.printStackTrace();        }    }

5、快速复制

public void moveFile(String source, String target) {        FileChannel in = null;        FileChannel out = null;        FileInputStream inStream = null;        FileOutputStream outStream = null;        try {            inStream = new FileInputStream(source);            outStream = new FileOutputStream(target);            in = inStream.getChannel();            out = outStream.getChannel();            in.transferTo(0, in.size(), out);        } catch (IOException e) {            e.printStackTrace();        } finally {            try {                inStream.close();                in.close();                outStream.close();                out.close();            } catch (IOException e) {                e.printStackTrace();            }        }    }

6、从指定地址进行文件下载

public void downloadFile(String source, String target) {        try {            URL url = new URL(source);            HttpURLConnection conn = (HttpURLConnection) url.openConnection();            conn.setDoInput(true);            conn.setDoOutput(true);            BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(target));            byte[] buffer = new byte[1204];            int byteRead = 0;            while ((byteRead = bis.read(buffer)) != -1) {                bos.write(buffer, 0, byteRead);            }            bos.flush();            bos.close();            bis.close();        } catch (MalformedURLException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (FileNotFoundException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }

7、浏览器执行文件下载

                File file=new File("D:/test.docx");                final HttpServletResponse response = getResonse();                response.setCharacterEncoding("UTF-8");        response.setHeader("Content-disposition", "attachment;filename=temp" + file.getName());                ServletOutputStream os = response.getOutputStream();                InputStream is = new FileInputStream(file);                byte[] buff = new byte[10240];                int batch;                while ((batch = is.read(buff)) != -1) {                    os.write(buff, 0, batch);                }                is.close();                os.close();

8、zip文件上传

// 文件上传    public boolean fileUpLoad(String upSource, String upTarget) {        try {            URL url = new URL(upTarget);            HttpURLConnection conn = (HttpURLConnection) url.openConnection();            conn.setDoInput(true);            conn.setDoOutput(true);            conn.setRequestMethod("POST");            conn.setRequestProperty("content-type", "application/zip");            BufferedOutputStream bos = new BufferedOutputStream(conn.getOutputStream());            // 读取文件上传到服务器            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(upSource));            byte[] bytes = new byte[1024];            int readByte = 0;            while ((readByte = bis.read(bytes, 0, 1024)) > 0) {                bos.write(bytes, 0, readByte);            }            bos.flush();            bos.close();            bis.close();        } catch (FileNotFoundException e) {            e.printStackTrace();            return false;        } catch (MalformedURLException e) {            e.printStackTrace();            return false;        } catch (IOException e) {            e.printStackTrace();            return false;        }        return true;    }

9、将文件夹打包成zip

// 压缩文件夹    private boolean fileToZip(String sourceFilePath, String zipFilePath, String fileName) {        File sourceFile = new File(sourceFilePath);        FileInputStream fis = null;        BufferedInputStream bis = null;        FileOutputStream fos = null;        ZipOutputStream zos = null;        if (!sourceFile.exists()) {            System.out.println("要压缩的文件夹不存在");            return false;        } else {            try {                File zipFile = new File(zipFilePath + "/" + fileName + ".zip");                if (zipFile.exists()) {                    zipFile.delete();// 如果有,先删除,实现覆盖                }                File[] sourceFiles = sourceFile.listFiles();                if (null == sourceFiles || sourceFiles.length < 1) {                    System.out.println("要压缩的文件夹没有文件存在");                    return false;                } else {                    fos = new FileOutputStream(zipFile);                    zos = new ZipOutputStream(new BufferedOutputStream(fos));                    byte[] bufs = new byte[1024 * 10];                    for (int i = 0; i < sourceFiles.length; i++) {                        // 创建ZIP实体,并添加进压缩包                        ZipEntry zipEntry = new ZipEntry(sourceFiles[i].getName());                        zos.putNextEntry(zipEntry);                        //=====================                        //使用这句可以确定编码,但是Java自带的包没有这个功能                        //所以必须用ant.jar                        //import org.apache.tools.zip.ZipEntry;                        //import org.apache.tools.zip.ZipOutputStream;                        zos.setEncoding("gbk");                        //====================                        // 读取待压缩的文件并写进压缩包里                        fis = new FileInputStream(sourceFiles[i]);                        bis = new BufferedInputStream(fis, 1024 * 10);                        int read = 0;                        while ((read = bis.read(bufs, 0, 1024 * 10)) != -1) {                            zos.write(bufs, 0, read);                        }                    }                }            } catch (FileNotFoundException e) {                e.printStackTrace();                throw new RuntimeException(e);            } catch (IOException e) {                e.printStackTrace();                throw new RuntimeException(e);            } finally {                // 关闭流                try {                    if (null != bis)                        bis.close();                    if (null != zos)                        zos.close();                } catch (IOException e) {                    e.printStackTrace();                    throw new RuntimeException(e);                }            }        }        return true;    }

10、a标签的onclick事件不能传除数字之外的参数。

standardFileName += "&nbsp;<a style='color:black;cursor:pointer;'onclick='downLoad(\""+source+"\");'>" + fileName + "</a>;";

解决方法:参数前后用双引号,转义字符后使用。

11、对字符串进行MD5加密

        //要加密的字符串        String str="what";        //确定计算方法        MessageDigest md=MessageDigest.getInstance("MD5");        BASE64Encoder encode=new BASE64Encoder();        //加密后的字符串        String newStr=encode.encode(md.digest(str.getBytes()));        System.out.println(newStr);

12、导入zip压缩包,并且解压

    try {        //filePath是要导入的压缩包地址;后面必须加Charset.forName("gbk");否则解压中文文件报错             ZipFile zipFile = new ZipFile(filePath, Charset.forName("gbk"));            // 获取ZIP文件里所有的entry            Enumeration entrys = zipFile.entries();            while (entrys.hasMoreElements()) {                entry = (ZipEntry) entrys.nextElement();                entryName = entry.getName();                String fileSize = String.valueOf(entry.getSize());                File targetFile = new File(target);                os = new FileOutputStream(targetFile);                byte[] buffer = new byte[4096];                int bytes_read = 0;                // 从ZipFile对象中打开entry的输入流                is = zipFile.getInputStream(entry);                while ((bytes_read = is.read(buffer)) != -1) {                    os.write(buffer, 0, bytes_read);                }            }        } catch (IOException err) {            System.err.println("解压缩文件失败: " + err);            flag = false;        }

13、读取xml文件信息
xml文件内容:

<prop>    <propname>标题</propname>    <propsign>Name</propsign>    <propvalue>发送测试</propvalue></prop><prop>    <propname>类型</propname>    <propsign>Type</propsign>    <propvalue>12</propvalue></prop><prop>    <propname>编号</propname>    <propsign>No</propsign>    <propvalue>11</propvalue></prop><prop>    <propname>成为日期</propname>    <propsign>sendDate</propsign>    <propvalue>2017-10-12</propvalue></prop><prop>    <propname>密级</propname>    <propsign>secret</propsign>    <propvalue>40</propvalue></prop><prop>    <propname>密级年</propname>    <propsign>secretYear</propsign>    <propvalue>12</propvalue></prop><prop>    <propname>缓急程度</propname>    <propsign>rapId</propsign>    <propvalue>急件</propvalue></prop>

获取到的都是propvalue的内容

        SAXReader reader = new SAXReader();        List<String> list = new ArrayList<>();        try {            Document doc = reader.read(new File(source));            Element root = doc.getRootElement();            for (Iterator i = root.elementIterator("prop"); i.hasNext();) {                Element foo = (Element) i.next();                for (Iterator j = foo.elementIterator("propvalue"); j.hasNext();) {                    Element joo = (Element) j.next();                    list.add(joo.getText());                }            }        } catch (MalformedURLException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (DocumentException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        return list;    
        //===================        //不使用循环一步步读下去        //===================        //内容:        <?xml version="1.0" encoding="utf-8"?>        <archman>        <DocSource>            <system>OA</system>            <type>普通文件</type>            <toDepts>                <dept>                    <deptname>what</deptname>                    <system>                        <name>阿斯蒂芬</name>                        <count>1</count>                    </system>                </dept>                <dept>                    <deptname>what</deptname>                    <system>                        <name>等等</name>                        <count>1</count>                    </system>                </dept>            </toDepts>        </DocSource>        //需要读取到阿斯蒂芬和等等
            InputStream in=new FileInputStream(new File(source));            Document doc = reader.read(in);            Element root = doc.getRootElement();            Element DocSource=(Element) root.elements().get(0);            List<Element> toDepts=DocSource.element("toDepts").elements();            String deptName="";            for (Element e : toDepts) {                if(deptName=="") {                    deptName=e.element("system").element("name").getText();                }else {                    deptName+=","+e.element("system").element("name").getText();                }            }

14、导入之前想让用户下载模板

<a href="downXmlFileInfo.action" style="color:blue;text-decoration:underline;cursor: pointer;">点击这里下载xml模板</a>
         String path=Environment.getWebRootPath()+"imp\\template\\";         String fileName="fileInfo.xml";         try {            final HttpServletResponse response = getResonse();            response.setCharacterEncoding("UTF-8");            File file = new File(path, fileName);            String name = file.getName();            // 需要定义为变量,如果tomcat中定义了Connector port="8080" URIEncoding="UTF-8"则不用转此code            String code = "ISO_8859_1";            name = new String(name.getBytes("UTF-8"), code);            //关键代码片            response.setHeader("Content-disposition", "attachment;filename=" + name);            ServletOutputStream os = response.getOutputStream();            //关键代码片            InputStream is = new FileInputStream(file);            byte[] buff = new byte[10240];            int batch;            while ((batch = is.read(buff)) != -1) {                os.write(buff, 0, batch);            }            is.close();            os.close();            } catch (IOException e) {                e.printStackTrace();            }

15、js对HTML页面table增删行
增加行:

    //.rows.length表示现在已有多少行,可以确保新增行的时候加在最后    //添加行    var newTr =  document.getElementById("fileUploadAttach").    insertRow(document.getElementById("fileUploadAttach").rows.length);      //添加行中的列    var newTd0 = newTr.insertCell();    newTd0.width="25px;";    newTd0.align="center";    var newTd1 = newTr.insertCell();    newTd1.width="300px;";    newTd1.align="left";    var newTd2 = newTr.insertCell();    newTd2.width="55px;";    //赋值    newTd0.innerHTML ="";    newTd1.innerHTML ="&nbsp;"+fileName;    newTd2.innerHTML ="<button onclick='deleteFile(this,\""+fileId+"\");return false;'  style='color:black;'>删除</button>";

删除所选行:

    function deleteFile(obj,fileId){    var index=obj.parentNode.parentNode.rowIndex;    var table = document.getElementById("fileUploadAttach");    table.deleteRow(index);    }          

删除增加的所有行:

    var tab1 = document.getElementById("fileUploadText");    var rowsText=tab1.rows.length;    //只能倒着删    if(rowsText>1){        for(var i=rowsText-1;i>0;i--){            tab1.deleteRow(i);        }    }

16、使用ajax的时候加上alert就成功,去掉alert就走不通,数据错误
原因:因为alert给了系统赋值的时间,所以有了alert就对了。
解决:ajax加上async:false,就可以了,表示同步。

17、在js中对字符串进行替换
问题:只能替换第一个
解决:使用正则替换

    var sendDate=$("[name='fileInfo.sendDate']").val();    //sendDate:2017-02-05  sendDateNum:20170205    var sendDateNum=Number(sendDate.replace(/-/g,""));    强转为数字,两个日期可以加减比较大小。

18、使用jQuery获取input的值获取不到
原因:字母写错了;命名出现重名,获取的不是你输入的那个;

19、js操作table,获取所选行的行号和某一格的值

<button onclick='deleteFile(this)'>删除</button>function deleteFile(obj){    var index=obj.parentNode.parentNode.rowIndex;//获取行号    var fileId=$("table").find("tr").eq(2).find("td").eq(4).text();//获取第2行第4列的值}

20、使用uploadServlet上传文件

        response.setContentType("text/html;charset=UTF-8");        FileItemFactory factory = new DiskFileItemFactory();        ServletFileUpload upload = new ServletFileUpload(factory);        upload.setHeaderEncoding("UTF-8");        List items = null;        try {            items = upload.parseRequest(request);        } catch (FileUploadException e1) {            e1.printStackTrace();        }        Iterator itr = items.iterator();        StringBuffer failMsg = new StringBuffer("");// 失败原因        while (itr.hasNext()) {            FileItem item = (FileItem) itr.next();            String fileName = item.getName();            fn = fileName.substring(fileName.lastIndexOf("/") + 1);            //扩展名            String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();            String newFileName = UUID.randomUUID().toString() + "." + fileExt;            try {                File uploadedFile = new File(savePath, newFileName);                item.write(uploadedFile);            } catch (Exception e) {                failMsg.append(";系统错误,上传失败");                return;            }        }        JSONObject obj = new JSONObject();        response.getWriter().write(obj.toJSONString());

21、文件加密与解密

    public static Key getKey() {          Key deskey = null;          try {              // 固定密钥              byte[] buffer = new byte[] { 0x47, 0x33, 0x43, 0x4D, 0x4F, 0x50, 0x31, 0x32 };              deskey = (Key) new SecretKeySpec(buffer, "DES");          } catch (Exception e) {              throw new RuntimeException("Error initializing SqlMap class. Cause: " + e);          }          return deskey;    }      /**        * 文件file进行加密并保存目标文件destFile中        *        * @param file   要加密的文件 如c:/test/srcFile.txt        * @param destFile 加密后存放的文件名 如c:/加密后文件.txt        */         public static void encrypt(String file, String destFile) throws Exception {           Cipher cipher = Cipher.getInstance( "DES/ECB/PKCS5Padding ");        cipher.init(Cipher.ENCRYPT_MODE, getKey());           InputStream is = new FileInputStream(file);           OutputStream out = new FileOutputStream(destFile);           CipherInputStream cis = new CipherInputStream(is, cipher);           byte[] buffer = new byte[1024];           int r;           while ((r = cis.read(buffer)) > 0) {               out.write(buffer, 0, r);           }           cis.close();           is.close();           out.close();         }      /**         * 文件采用DES算法解密文件         *         * @param file 已加密的文件 如c:/加密后文件.txt         * @param destFile         * 解密后存放的文件名 如c:/ test/解密后文件.txt         */          public static void decrypt(String source){           InputStream is=null;        OutputStream out=null;        CipherOutputStream cos=null;        File file=new File(source);        File destFile=new File("D://12"+source.substring(source.lastIndexOf(".")));        try {            Cipher cipher = Cipher.getInstance("DES");                cipher.init(Cipher.DECRYPT_MODE, getKey());              is = new FileInputStream(file);                out = new FileOutputStream(destFile);                cos = new CipherOutputStream(out, cipher);                byte[] buffer = new byte[1024];                int r;                while ((r = is.read(buffer)) >= 0) {                    System.out.println();                   cos.write(buffer, 0, r);                }        } catch (Exception e) {            // TODO Auto-generated catch block            e.printStackTrace();        } finally {             try {                cos.close();                    out.close();                    is.close();                 file.delete();                 destFile.renameTo(file);            } catch (IOException e) {                e.printStackTrace();            }        }        System.out.println("解密完成");       }

22、在for循环中操作文件无效
解决:for循环采用倒序就可以了。

23、文件解压后文件持续占用
问题一:压缩包删除不了
解决:除了关闭流,还要关闭zipFile。zipFile.close();
问题二:解压好的文件操作时表示占用
解决:关闭流之后加上System.gc();

24、jedis使用
jedis.properties:

host=193.122.1.21port=6379maxTotal=20maxIdle=10

JedisUtils.java:

public class JedisUtils {    private static int maxTotal = 0;    private static int maxIdle = 0;    private static String host = null;    private static int port = 0;    private static JedisPoolConfig config = new JedisPoolConfig();    static {        // 读取配置文件        InputStream in = JedisUtils.class.getClassLoader().getResourceAsStream("jedis.properties");        Properties pro = new Properties();        try {            pro.load(in);        } catch (IOException e) {            e.printStackTrace();        }        maxTotal = Integer.parseInt(pro.getProperty("maxTotal"));        maxIdle = Integer.parseInt(pro.getProperty("maxIdle"));        port = Integer.parseInt(pro.getProperty("port"));        host = pro.getProperty("host");        config.setMaxTotal(maxTotal);        config.setMaxIdle(maxIdle);    }    private static JedisPool pool = new JedisPool(config, host, port);    // 提供一个返回池子的方法    public static JedisPool getPool() {        return pool;    }    // 获得一个jedis资源方法    public static Jedis getJedis() {        return pool.getResource();    }    // 关闭的方法    public static void close(Jedis jedis) {        if (jedis != null) {            jedis.close();        }    }}

25、Java实现控制打开网页链接及关闭

        String site="http://mp.weixin.qq.com/s/5WDhPf1meNCZ4YVyXbJt2Q";        try {              Desktop desktop = Desktop.getDesktop();              URI url = new URI(site);              for (int i = 0; i < 10; i++) {                //执行这里就可以打开了                desktop.browse(url);            }            Thread.sleep(8000);            //用360chrome.exe打开,所以这里关闭这个。            Runtime.getRuntime().exec("taskkill /F /IM 360chrome.exe");         } catch (Exception e) {            e.printStackTrace();        }

26、oracle日期操作

//date转换成timestampSELECT CAST(SYSDATE AS TIMESTAMP) FROM DUAL;//timestamp类型转换为date类型SELECT CAST(CREATE_TIME AS DATE) FROM XTABLE;//计算date类型之间相差天数SELECT ROUND(DATE1-DATE2) FROM XTABLE;//计算timestamp类型之间相差的天数SELECT ROUND(CAST(TIMESTAMP1 AS DATE)-CAST(TIMESTAMP2 AS DATE)) FROM XTABLE;

27、存数据库前,转换date或String到timestamp类型

        //date        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");        Timestamp.valueOf(sdf.format(new Date()));        //字符串        String str="2017-10-11";        Timestamp.valueOf(str+" 00:00:00");

28、项目添加定时器

//1、新建一个class类,实现servletContextListener接口,类中写定时器和调用的方法//2、在web.XML中配置监听器就可以了public class clearFileTimer implements ServletContextListener {    @Override    public void contextDestroyed(ServletContextEvent arg0) {        // TODO Auto-generated method stub    }    @Override    public void contextInitialized(ServletContextEvent arg0) {        Runnable runnable = new Runnable() {            public void run() {                clearFile clear = new clearFile();                try {                    while (true) {                        // 10天执行一次删除操作                        long sleep = 10 * 86400 * 1000;                        Thread.sleep(sleep);                        clear.clearIt();// 调用的方法                    }                } catch (Exception e) {                    e.printStackTrace();                }            }        };        Thread thread = new Thread(runnable);        thread.start();    }}        //=============        //web.xml文件        //=========        <listener>            <listener-class>                com.test.what.impl.clearFileTimer            </listener-class>        </listener>

29、定时器第二种写法

import javax.servlet.ServletContextEvent;import javax.servlet.ServletContextListener;import java.util.Timer;import java.util.TimerTask;public class updateStateTimer implements ServletContextListener{    @Override    public void contextDestroyed(ServletContextEvent arg0) {    }    @Override    public void contextInitialized(ServletContextEvent arg0) {        updateState t = new updateState();//默认执行updateState这个类中的run方法        Timer timer=new Timer(true);        long period=24*60*60*1000;        timer.schedule(t, 20000, period); //t表示执行的类(中的run方法),20000表示延迟,period表示间隔    }}class updateState extends TimerTask {    @Override    public void run() {        new SendListMan().updateStateEveryday();    }}

30、断点续传与非断电续传两端写法

//接收文件端:public void wsReceive(String fileByte,String fileName) {    //fileByte表示文件转换成的字符串        //文件名称和路径        String zipSource = "D:/"+fileName;        FileOutputStream fos = null;        try {            BASE64Decoder decoder = new BASE64Decoder();            byte[] bytes = decoder.decodeBuffer(fileByte);            fos = new FileOutputStream(zipSource,true);//后面加true,表示文件存在时,内容叠加(断点续传)            fos = new FileOutputStream(zipSource);//表示产生新的文件,会覆盖之前的所有内容(非断点续传)            fos.write(bytes);            fos.flush();            fos.close();        } catch (Exception e) {            e.printStackTrace();        }    }
        //非断点续传发送文件端:        FileInputStream fis = new FileInputStream(file);        StringBuffer sb = new StringBuffer();        byte[] buffer = new byte[(int) file.length()];        fis.read(buffer);//一次性将文件全部转换成字符串,然后执行发送        String ret = new BASE64Encoder().encode(buffer);        sb.append(ret);        String result = client.invoke(methodName, new Object[] { sb.toString() })[0].toString();
//断点续传发送文件端:            StringBuffer sb = new StringBuffer();            FileInputStream fis = new FileInputStream(file);            fis.skip(startIndex);// 发送之前先定位到文件的已有长度位置,如果是第一次发送那就是0            byte[] buffer = new byte[BUFFER_LENGTH];            byte[] bufferTemp;            int count;            String result = "";            //在while中,每读一次,就调一次接收端的方法            while ((count = fis.read(buffer)) > 0) {                String ret = "";                if (count < BUFFER_LENGTH) {    //if方法是对最后一次不够一个buffer时的处理                    bufferTemp = new byte[count];                    for (int j = 0; j < count; j++) {                        bufferTemp[j] = buffer[j];                    }                } else {                    bufferTemp = buffer;                }                ret = new BASE64Encoder().encode(bufferTemp);                sb = new StringBuffer();                sb.append(ret);    result = client.invoke(methodName, new Object[] { sb.toString(), orgFileName })[0].toString();              }

31、webService接口开发

//===============//1、接口//===============import javax.jws.WebMethod;import javax.jws.WebService;import javax.jws.soap.SOAPBinding;@WebService@SOAPBinding(style = SOAPBinding.Style.RPC)public interface wsReceiveFile {    @WebMethod    public String whatkk(String str);}//===============//2、实现类//===============import javax.jws.WebService;import javax.jws.soap.SOAPBinding;@WebService(endpointInterface = "com.as.dsf.wsReceiveFile")@SOAPBinding(style = SOAPBinding.Style.RPC)public class wsReceiveFileImpl implements wsReceiveFile {    @Override    public String whatkk(String str) {        // TODO Auto-generated method stub        return null;    }}//===============//3、web.xml写法//===============    <listener>        <listener-class>            com.sun.xml.ws.transport.http.servlet.WSServletContextListener        </listener-class>    </listener>    <servlet>        <servlet-name>wsReceiveFile</servlet-name>        <servlet-class>            com.sun.xml.ws.transport.http.servlet.WSServlet        </servlet-class>    </servlet>    <servlet-mapping>        <servlet-name>wsReceiveFile</servlet-name>        <url-pattern>/ws/receiveFile</url-pattern>    </servlet-mapping>//===============//4、sun-jaxws.xml写法//===============<?xml version="1.0" encoding="UTF-8"?><endpoints xmlns="http://java.sun.com/xml/ns/jax-ws/ri/runtime" version="2.0"> <endpoint name="wsSendFile" implementation="com.imp.wsSendFileImpl" url-pattern="/ws/sendFile"/> <endpoint name="wsReceiveFile" implementation="com.imp.wsRFileImpl" url-pattern="/ws/receiveFile"/></endpoints></xml>
阅读全文
0 0