How to access share folder in windows through android and read files

后端 未结 2 1376
攒了一身酷
攒了一身酷 2020-12-03 12:54

I need to connect from my Android phone to a Windows PC share and access files. I saw some sample apps in Android market that access share folders using smb/samba. But I hav

相关标签:
2条回答
  • 2020-12-03 13:33

    Google has released a simple, free Samba client. It is on github so you can have a look and use whatever you need out of that: https://github.com/google/samba-documents-provider

    The other option is JCIFS: https://jcifs.samba.org/. There you can find the library and examples on how to use it.

    I used JCIFS. Here is an example from my code which reads files from a folder in a windows share:

        TreeMap<Date, String> filesInfo = new TreeMap<Date, String>();
        NtlmPasswordAuthentication auth = null;
            UniAddress dc = UniAddress.getByName(m_dataHostIp);
            if(m_userName.length() > 0 && m_password.length() > 0)
                auth = new NtlmPasswordAuthentication(m_domain + ";" + m_userName + ":" + m_password);
            else
                auth = new NtlmPasswordAuthentication(m_domain, null, null);
            SmbSession.logon(dc, auth);
    
            SmbFile file = new SmbFile(m_foldername, auth);
            SmbFile[] files = file.listFiles();
            for (int i = 0; i < files.length; i++)
            {
               String fileName = files[i].getName();
               String extension=fileName.substring(fileName.lastIndexOf(".") + 1);
               logInfo(TAG + " " + fileName + "\n");
               Date fileTime = new Date(files[i].getDate()); 
                if(m_fileExtension.contains(extension))
                    filesInfo.put(fileTime, fileName);
    
            }
    

    The code posted above works. It allows you to connect to the share, authenticate (username and password that you know) and get the list of the files. At the root of jcif file access is the SmbFile which has all the info you need to access files in the share. All you need is in your build.gradle for the app add:

    dependencies {
        implementation files('libs/jcifs-1.3.19.jar')
    }
    

    and in your implementation file:

    import jcifs.smb.NtlmPasswordAuthentication;
    import jcifs.smb.SmbFile;
    import static jcifs.smb.SmbFile.FILE_SHARE_DELETE;
    import static jcifs.smb.SmbFile.FILE_SHARE_READ;
    import static jcifs.smb.SmbFile.FILE_SHARE_WRITE;
    
    0 讨论(0)
  • 2020-12-03 13:43

    You need to get JCIFS and use SmbFile class to interact with files over the network,

    http://lists.samba.org/archive/jcifs/2007-September/007465.html

    that is a quick example of how to list files, of coarse you need internet permission on. So Far though everytime I try to call SmbFile.listFiles(); I get an UnknownHostException, However others seam to be able to do it with no problem, this might work for you, try it!

    0 讨论(0)
提交回复
热议问题