最近用户需要需要程序定时去读取另外一台机器的EXCEL文件,我出了个解决方案:因为是windows服务器,所以我在本地映射了一个盘Z然后就想读取本机的文件那样读取,结果临到上生产的时候发现只要服务器休眠后映射就会被断开,导致读取失败,找不到文件。
后来多方google之后,发现SMB协议 ,屌丝程序员的福音啊。
SMB协议(百度百科) : http://baike.baidu.com/link?url=yEZWDgVzifVDdxooeiuFu8u3PFYrU5W-5_E_kqF_mPgadRI9MeUeUv5XBX1e4r7ghpbM3lmSTY3qhnf27c0FMq、
JAVA中的类库:jcifs该协议做了很好的支持:
不说了,贴代码:
/** * 以Smb协议读取共享文件下文件 * @param fileName * @return * @throws Exception */ private InputStream getSmbRemoteFile(String fileName) throws Exception { String hostIp = SysConfig.getInstance().getValue("dps_host_ip"); String domain = SysConfig.getInstance().getValue("dps_domain"); String userName = SysConfig.getInstance().getValue("dps_username"); String pwd = SysConfig.getInstance().getValue("dps_password"); UniAddress dc = UniAddress.getByName(hostIp); NtlmPasswordAuthentication authentication = new NtlmPasswordAuthentication( domain, userName, pwd); SmbSession.logon(dc, authentication); String fileUrl = "smb://" + hostIp + "/mfgcom/Commons/DPS/" + fileName; logger.info(String.format("开始从远程地址:%s以SMb协议读取数据", fileUrl)); SmbFile remoteFile = new SmbFile(fileUrl, authentication); // remoteFile.connect(); // 尝试连接 logger.info("remoteFile path:" + remoteFile.getPath()); InputStream in = new BufferedInputStream(new SmbFileInputStream( remoteFile)); if (null == in) { logger.error(String.format("远程(%s)读取数据失败!", fileUrl)); } return in; }