Java calls directly read and write samba server

 

	/**
	 * Synchronize files to the smb server, a total of four samba servers
	 * @param files list of synced files
	 * @param ctx
	 */
	public static void _fileSync(String[] files,String SmbUrl){
		try{

			
			SmbFile remote = new SmbFile(SmbUrl);

			for (int i = 0; i < files.length; i++) {
				File file = new File(files[i]);
				String filePath = file.getAbsolutePath();
				//System.out.println(filePath);
	
				// sync to file server
				System.out.println(Constants.REALPATH);
				String smbFilePath = filePath.substring(Constants.REALPATH.length()+1);
				//System.out.println(smbFilePath);
				String smbFolderPath = smbFilePath.substring(0, smbFilePath.lastIndexOf(File.separator));
				//System.out.println(smbFolderPath);
				//System.out.println(smbFolderPath.replace('\\', '/'));
				SmbFile remoteFolder = new SmbFile(remote, smbFolderPath.replace('\\', '/'));
				//System.out.println(remote);
				//System.out.println(remoteFolder);
				if (!remoteFolder.exists()) {
					remoteFolder.mkdirs();
				}
								
				SmbFile remoteFile = new SmbFile(remote, smbFilePath);
	
				
				if (!remoteFile.exists()) {
					remoteFile.createNewFile();
				}


				FileInputStream fis = new FileInputStream(file);
				SmbFileOutputStream sfos = new SmbFileOutputStream(remoteFile);

				int c;
				byte[] buf = new byte[2048];
				while ((c = fis.read(buf)) != -1) {
					sfos.write(buf, 0, c);

				}
				sfos.flush();

				fis.close();
	
				// delete local file
				file.delete();
			}
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}

 

where the SmbUrl format is

smb://{username}:{passwd}@{ip}/{smbshare}/

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326690186&siteId=291194637