javascript学习指南|java用jcifs实现从ubuntu向windows服务器上传下载文件

时间:2019-09-26  来源:Windows服务器  阅读:

CIFS(Common Internet File System)全称是通用Internet文件系统,由于在windows主机之间进行网络文件共享是通过使用微软公司自己的CIFS服务实现的,所以直接通过//ip/sharefolder/file.txt这种格式即可实现共享,但是跨到linux这边就要用smb://ip/sharefolder/file.txt这种,即使用smb协议。到java程序中,就要用迂回的办法来实现了,那就是jcifs。

Jcifs是CIFS在JAVA中的一个实现,是samba组织本着linux的精神,负责维护开发的一个开源项目。这个项目专注于使用java语言对cifs协议的设计和实现。他们将jcifs设计成为一个完整的,丰富的,具有可扩展能力且线程安全的客户端库。这一库可以应用于各种java虚拟机访问遵循CIFS/SMB网络传输协议的网络资源。类似于java.io.File的接口形式,在多线程的工作方式下被证实是有效而轻易使用的。
1.usage

进入http://jcifs.samba.org/,在左边Links找到Download链接,点进去是个文件共享的目录,下载最新版(win用zip,linux用tgz)。

解压会看到一些example和docs说明文件,还有jcifs的jar包。复制下载到的jcifsxx.xx.jar到工程目录下,并在builder path中包含该jar包。和其他第三方库一样,在程序中调用jar包提供的各种接口。
2.auth

认证是程序中最容易遇到错误的部分,因为公司本地有域认证的关系,所以在认证方面费了一番功夫,并且碰到许多奇怪的问题。总结起来有3种错误:

1、本地文件或者路径不存在

path + (No such file or directory)

2、目标文件/路径不存在

access denied
The system cannot find the path specified.

3、用于验证的用户名密码不对

Logon failure: unknown user name or bad password.
The specified network password is not correct.

3.upload

接下来就是上传了.完整程序如下:

public static void main(String argv[]) throws Exception {
    String local = "/home/Desktop/yourlocalFile.name";
    String remote = "smb://yoursharefolder/SMBtest.doc";
    copyTo(local, remote);
}

private static void copyTo(String localName, String remoteName) {
    OutputStream fileOutputStream = null;
    FileInputStream fileInputStream = null;
    NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("",
            "username", "password");
    try {
        SmbFile remoteFile = new SmbFile(remoteName, auth);
        SmbFile remoteDir = new SmbFile(remoteFile.getParent(), auth);
        // create remote folder if not exist
        if (!remoteDir.exists())
            remoteDir.mkdirs();
        // create remote file
        if (!remoteFile.exists())
            remoteFile.createNewFile();
        remoteFile.setReadWrite();
        byte[] buf;
        int len;
        System.out.println("Now copying " + localName);
        try {
            fileInputStream = new FileInputStream(localName);
            fileOutputStream = remoteFile.getOutputStream();

            buf = new byte[16 * 1024 * 1024];
            while ((len = fileInputStream.read(buf)) > 0) {
                fileOutputStream.write(buf, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            fileInputStream.close();
            fileOutputStream.close();
            System.out.println("Upload " + remoteName + ", done");
        }
    } catch (Exception e) {
        System.err.println("Exception occured: " + e.getMessage());
    }
}

javascript学习指南|java用jcifs实现从ubuntu向windows服务器上传下载文件

http://m.bbyears.com/caozuoxitong/69454.html

推荐访问:java学习路线
相关阅读 猜你喜欢
本类排行 本类最新