這是本文件的舊版!


JCIFS

JCIFS是java-based存取網路芳鄰通訊協定的API。

之所以接觸這個API,是因為很好奇Windows管理工具psexec,能將Local程式放到Remote並執行的做法。後來看到類似工具paexec程式碼,與經過自己的測試,發現原理是將程式複製到遠端的管理共享資料夾,再透過WMI呼叫外部程式。

接下來將說明我有使用的API。

首先至link下載library。接下來就是寫寫寫。

Create File

大部分的操作都可以透過SmbFile類別完成。而與遠端的機器認證,是透過NTLM通訊協定

	private static NtlmPasswordAuthentication createAuth(String aUser, String aPasswd){
		StringBuffer sb = new StringBuffer(aUser); 
		sb.append(':').append(aPasswd);
		return new NtlmPasswordAuthentication(sb.toString());
	}
 
	public static SmbFile createSmbFile(String aUser, String aPasswd, String aTarget) throws IOException {
		NtlmPasswordAuthentication auth = createAuth(aUser, aPasswd);
		return new SmbFile(aTarget, auth);
	}
在建立完SmbFile物件後,剩下其實就和操作一般檔案無異。
	public static void createFile(String aUser, String aPasswd, String aTarget, String aContent) throws IOException {
		SmbFile sFile = createSmbFile(aUser, aPasswd, aTarget);
		SmbFileOutputStream sfos = null;
		try {
			sfos = new SmbFileOutputStream(sFile);
			sfos.write(aContent.getBytes());
		} finally {
			close(sfos);
		}
	}
最後是關閉串流的處理。
	private static void close(Closeable aCloseable){
		if( aCloseable == null )
			return;
 
		try {
			aCloseable.close();
		} catch (IOException e) {
			//  log exception
		}
	}

Delete File

刪除檔案:

	public static void deleteFile(String aUser, String aPasswd, String aTarget) throws IOException {
		SmbFile sFile = createSmbFile(aUser, aPasswd, aTarget);
		sFile.delete();
	}

Exist

確認檔案是否存在:

	public static boolean exists(String aUser, String aPasswd, String aTarget) throws IOException {
		SmbFile sFile = createSmbFile(aUser, aPasswd, aTarget);
		return sFile.exists();
	}

Copy File

複製本地檔案到遠端:

	public static void copyFileTo(String aUser, String aPasswd, String aSource, String aTarget) throws IOException {
		SmbFile sFile = createSmbFile(aUser, aPasswd, aTarget);
		SmbFileOutputStream sfos = null;
		FileInputStream fis = null;
		try {
			sfos = new SmbFileOutputStream(sFile);
			fis = new FileInputStream(new File(aSource));
 
			byte[] buf = new byte[1024];
			int len;
			while(( len = fis.read(buf) )> 0 ){
				sfos.write(buf, 0, len);
			}
		} finally {
			close(sfos);
			close(fis);
		}
	}
複製遠端檔案到本地:
public static void copyFileFrom(String aUser, String aPasswd, String aSource, String aTarget) throws IOException {
		SmbFile sFile = createSmbFile(aUser, aPasswd, aSource);
		SmbFileInputStream sfis = null;
		FileOutputStream fos = null;
		try {
			sfis = new SmbFileInputStream(sFile);
			fos = new FileOutputStream(new File(aTarget));
 
			byte[] buf = new byte[1024];
			int len;
			while(( len = sfis.read(buf) )> 0 ){
				fos.write(buf, 0, len);
			}
		} finally {
			close(sfis);
			close(fos);
		}
	}