1. 程式人生 > 其它 >Android 使用 JCIFS 訪問共享檔案

Android 使用 JCIFS 訪問共享檔案

1.訪問共享檔案,一定要寫在”子執行緒”,不要寫在主執行緒裡面,不然一直閃退。為了這個不知道掉了幾根頭髮

new Thread(new Runnable() {
                        @Override

                        public void run() {
                            SmbToUpdate();
                        }
                    }).start();

  

public  void  SmbToUpdate()
    {

        InputStream 
in = null ; ByteArrayOutputStream out = null ; try { NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("smb://192.168.XX.XX","使用者名稱", "密碼"); SmbFile remoteFile = new SmbFile("smb://192.168.XX.XX/Share/AutoUpdater.xml", auth); remoteFile.connect();
//嘗試連線 in = new BufferedInputStream(new SmbFileInputStream(remoteFile)); out = new ByteArrayOutputStream((int)remoteFile.length()); //讀取檔案內容 byte[] buffer = new byte[4096]; int len = 0; //Read length while ((len = in.read(buffer, 0, buffer.length)) != - 1
) { out.write(buffer, 0, len); } out.flush(); //方法重新整理此輸出流並強制將所有緩衝的輸出位元組被寫出 byte[] data= out.toByteArray(); String Xml = new String(data); } catch (Exception e) { String msg = "Download a remote file error: " + e.getLocalizedMessage(); System.out.println(msg); } finally { try { if(out != null) { out.close(); } if(in != null) { in.close(); } } catch (Exception e) { int a=1; } } }