java如何访问局域网共享文件?

java如何访问局域网共享文件?,第1张

java访问共享文件夹,读取局域网中一台机器的共穗悔享目录中的文件,需要jcifs-1.1.11.jar的支持,使用SMB协议,以宴明下是实现了远程读取文件的功能代码:

package junit

import jcifs.smb.SmbFile

/**   

 * java访问局域网共享目录

 *

 * @author administrator

 * @version 1.0 2015-7-6 猜祥正

 */

public class SmbTest {

    public static void main(String[] args) throws Exception {

        //smb://xxx:[email protected]/testIndex/  

        //xxx:xxx是共享机器的用户名密码

        String url="smb://192.168.2.188/testIndex/"

        SmbFile file = new SmbFile(url)

        if(file.exists()){

            SmbFile[] files = file.listFiles()

            for(SmbFile f : files){

                System.out.println(f.getName())

            }

        }

    }

}

不好实现,网上有方法说用FTP,但是不会用啊,找了一个public static void forcdt(String dir){InputStream in = nullOutputStream out = nullFile localFile = new File(dir)try{//创建file类 传入本地文件路岩银源径//获得本地文件的名字String fileName = localFile.getName()//将本地文件的名字和远程目录的名字拼接在一起//确保上传后的文件于本地文件名字相同SmbFile remoteFile = new SmbFile("smb://粗态administrator:[email protected]/e$/aa/")//创建读取缓冲流把本地的文件与程序连接在一起in = new BufferedInputStream(new FileInputStream(localFile))//创建一个写出缓冲流(注意jcifs-1.3.15.jar包 类名为Smb开头的类为控制远程共享计算机"io"包)//将远程的文件路径搏滑传入SmbFileOutputStream中 并用 缓冲流套接out = new BufferedOutputStream(new SmbFileOutputStream(remoteFile+"/"+fileName))//创建中转字节数组byte[] buffer = new byte[1024]while(in.read(buffer)!=-1){//in对象的read方法返回-1为 文件以读取完毕out.write(buffer)buffer = new byte[1024]}}catch(Exception e){e.printStackTrace()}finally{try{//注意用完 *** 作io对象的方法后关闭这些资源,走则 造成文件上传失败等问题。!out.close()in.close()


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/tougao/12191390.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-21
下一篇 2023-05-21

发表评论

登录后才能评论

评论列表(0条)

保存