将远程目录中的文件进行读取

本文介绍了一种通过Java实现远程文件共享的方法,包括如何利用SMB协议读写远程共享目录中的文件,并提供了具体的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

通常将远程共享目录中进行读取的时候,需要输入登陆的用户和密码,来判断用户是否有权限进行访问,在代码中需要将用户的信息设置进去,来获取该目录的访问权限等;代码如下:

 

public class CopyNetFileUtil {
 private static final Logger logger = Logger.getLogger(CopyNetFileUtil.class);

 /**
  * sample
  * @param inputPath e:/remarks.xls
  * @param outputPath /shared/ocean/remarks.xls
  * @throws Exception
  */
 public static void writeShareFile(String inputPath, String outputPath) throws Exception {
  try {
   SmbFile smbFile = new SmbFile("smb://用户:密码@IP地址" + outputPath);
   File file = new File(inputPath);
   int length = (int) file.length(); // get file size
   FileInputStream fi = new FileInputStream(file);
   byte buffer[] = new byte[2048];
   SmbFileOutputStream out = new SmbFileOutputStream(smbFile);
   while (fi.read(buffer) != -1) {
    out.write(buffer);
   }
   fi.close();
   out.flush();
   out.close();

  } catch (MalformedURLException e) {
   logger.error(e);
   throw e;
  }

 }

public static File readFromSmb(
  String userName,
  String passWd,
  String ip,
  String smbFilePath,
  String localpath) {
  File localfile = null;
  InputStream bis = null;
  OutputStream bos = null;
  String smbMachine = null;
  try {
   smbMachine = "smb://" + userName + ":" + passWd + "@" + ip + smbFilePath;
   SmbFile rmifile = new SmbFile(smbMachine);
   String filename = rmifile.getName();
   bis = new BufferedInputStream(new SmbFileInputStream(rmifile));
   localfile = new File(localpath + filename);
   System.out.println("localfile==" + localfile);
   bos = new BufferedOutputStream(new FileOutputStream(localfile));
   int length = rmifile.getContentLength();
   System.out.println("length==" + length);
   byte[] buffer = new byte[2048];
   while (bis.read(buffer) != -1) {
    bos.write(buffer);
   }
   bos.flush();
  } catch (Exception e) {
   e.printStackTrace();

  } finally {
   try {
    bos.close();
    bis.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
  return localfile;
 }

 public static void main(String[] args) {
  String network_output_ip = "IP地址";
  String network_output_id = "用户名";
  String network_output_password = "密码";
  String network_output_path = "共享文件路径和文件名";

  try {
   CopyNetFileUtil.writeShareFile("d:/test.txt", network_output_path);
  } catch (Exception e) {
   e.printStackTrace();
  }

 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值