java利用SMB读取远程文件的方法
本文实例为大家分享了java利用SMB读取远程文件的具体代码,供大家参考,具体内容如下
packagecom.yss.test.FileReadWriter; importjava.io.BufferedInputStream; importjava.io.BufferedOutputStream; importjava.io.File; importjava.io.FileInputStream; importjava.io.FileOutputStream; importjava.io.IOException; importjava.io.InputStream; importjava.io.OutputStream; importjava.net.MalformedURLException; importjcifs.smb.SmbFile; importjcifs.smb.SmbFileInputStream; importjcifs.smb.SmbFileOutputStream; publicclassRemoteAccessData{ /** *@paramargs *@throwsIOException */ publicstaticvoidmain(String[]args)throwsIOException{ smbGet1("smb://192.168.75.204/test/新建文本文档.txt"); smbGet("smb://192.168.75.204/test/新建文本文档.txt","e:/"); } /** *方法一: * *@paramremoteUrl *远程路径smb://192.168.75.204/test/新建文本文档.txt *@throwsIOException */ publicstaticvoidsmbGet1(StringremoteUrl)throwsIOException{ SmbFilesmbFile=newSmbFile(remoteUrl); intlength=smbFile.getContentLength();//得到文件的大小 bytebuffer[]=newbyte[length]; SmbFileInputStreamin=newSmbFileInputStream(smbFile); //建立smb文件输入流 while((in.read(buffer))!=-1){ System.out.write(buffer); System.out.println(buffer.length); } in.close(); } //从共享目录下载文件 /** *方法二: *路径格式:smb://192.168.75.204/test/新建文本文档.txt *smb://username:password@192.168.0.77/test *@paramremoteUrl *远程路径 *@paramlocalDir *要写入的本地路径 */ publicstaticvoidsmbGet(StringremoteUrl,StringlocalDir){ InputStreamin=null; OutputStreamout=null; try{ SmbFileremoteFile=newSmbFile(remoteUrl); if(remoteFile==null){ System.out.println("共享文件不存在"); return; } StringfileName=remoteFile.getName(); FilelocalFile=newFile(localDir+File.separator+fileName); in=newBufferedInputStream(newSmbFileInputStream(remoteFile)); out=newBufferedOutputStream(newFileOutputStream(localFile)); byte[]buffer=newbyte[1024]; while(in.read(buffer)!=-1){ out.write(buffer); buffer=newbyte[1024]; } }catch(Exceptione){ e.printStackTrace(); }finally{ try{ out.close(); in.close(); }catch(IOExceptione){ e.printStackTrace(); } } } //向共享目录上传文件 publicstaticvoidsmbPut(StringremoteUrl,StringlocalFilePath){ InputStreamin=null; OutputStreamout=null; try{ FilelocalFile=newFile(localFilePath); StringfileName=localFile.getName(); SmbFileremoteFile=newSmbFile(remoteUrl+"/"+fileName); in=newBufferedInputStream(newFileInputStream(localFile)); out=newBufferedOutputStream(newSmbFileOutputStream(remoteFile)); byte[]buffer=newbyte[1024]; while(in.read(buffer)!=-1){ out.write(buffer); buffer=newbyte[1024]; } }catch(Exceptione){ e.printStackTrace(); }finally{ try{ out.close(); in.close(); }catch(IOExceptione){ e.printStackTrace(); } } } //远程urlsmb://192.168.0.77/test //如果需要用户名密码就这样: //smb://username:password@192.168.0.77/test }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。