Java reads and writes Windows shared folders.

Source: Internet
Author: User

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Projects often require access to shared folders, such as shared folders that store photos, files, and so on. So how do you read and write Windows shared folders using Java?

Java can use the JCIFS framework to read and write Windows shared Folders, which allows us to access remote folders like a local folder.

Jcifs's website: http://jcifs.samba.org/

Jcifs is an open-source framework developed using pure Java to access remote folders through the SMB protocol. The framework supports both Windows shared Folders and Linux shared folders, but the Linux shared folder requires the installation of Samba Services software (official website: http://www.samba.org/).

SMB (Server Messages block, information service blocks) is a kind of communication protocol for sharing files and printers on LAN, which provides shared services of files and printers among different computers in LAN. The SMB protocol is a client/server protocol that allows clients to access shared file systems, printers, and other resources on the server. By setting up "NetBIOS over TCP/IP", Samba will not only share resources with local network hosts, but also share resources with computers around the world.

This article focuses on how to access Windows shared Folders using Java.

First find a Windows machine, create a folder in any location: SharedFolder, and set to share, set the shared user name: Share, Password: admin.

(Windows7 Settings shared folder method: HTTP://HI.BAIDU.COM/51_XUEXI/ITEM/5A90A20CD732A8CE75CD3C6D)

The code for accessing shared folders using Java SMB is the same regardless of the shared folder for Windows or Linux, except that Windows has a different way of configuring shared folders with Linux.

The test code is as follows:

[Java]View Plaincopy print?
  1. InputStream in = null;
  2. OutputStream out = null;
  3. try {
  4. //Get Pictures
  5. File LocalFile = new File ("c:/test.jpg");
  6. String Remotephotourl = "Smb://share:[email protected]/sharedfolder/";//shared directory where the picture is stored
  7. SimpleDateFormat FMT = new SimpleDateFormat ("Yyyymmddhhmmsssss_");
  8. Smbfile remotefile = new Smbfile (Remotephotourl + "/" + Fmt.format (new Date ()) + localfile.getname ());
  9. Remotefile.connect (); //try to connect
  10. in = new Bufferedinputstream (new FileInputStream (LocalFile));
  11. out = new Bufferedoutputstream (new Smbfileoutputstream (RemoteFile));
  12. byte[] buffer = new byte[4096];
  13. int len = 0; //Read length
  14. While (len = in.read (buffer, 0, buffer.length))! =-1) {
  15. Out.write (buffer, 0, Len);
  16. }
  17. Out.flush (); //Refresh buffered output stream
  18. }
  19. catch (Exception e) {
  20. String msg = "error occurred:" + e.getlocalizedmessage ();
  21. SYSTEM.OUT.PRINTLN (msg);
  22. }
  23. finally {
  24. try {
  25. if (out! = null) {
  26. Out.close ();
  27. }
  28. if (in = null) {
  29. In.close ();
  30. }
  31. }
  32. catch (Exception e) {}
  33. }
        InputStream in = null;        OutputStream out = null;            try {//get picture file LocalFile = new file ("C:/test.jpg"); String Remotephotourl = "smb://share:[email protected]/sharedfolder/";            The shared directory where the images are stored simpledateformat FMT = new SimpleDateFormat ("Yyyymmddhhmmsssss_");            Smbfile remotefile = new Smbfile (Remotephotourl + "/" + Fmt.format (new Date ()) + localfile.getname ()); Remotefile.connect ();            Try to connect in = new Bufferedinputstream (new FileInputStream (LocalFile));            out = new Bufferedoutputstream (new Smbfileoutputstream (RemoteFile));            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 ();            Flush buffered output stream} catch (Exception e) {String msg = "Error occurred:" + e.getlocalizedmessage ();    SYSTEM.OUT.PRINTLN (msg);    } finally {try {if (out! = null) {out.close ();                } if (in = null) {in.close (); }} catch (Exception e) {}}

The above code uses the Smbfile class provided by the JCIFS framework, which is similar to the Java file class, and uses this class object to handle the read and write of remote files. Use the file object to read the local file, and then use the Smbfile object to write to the remote file. The Smbfile Connect () method tries to connect to the remote folder and throws a connection exception if the account or password is incorrect.

When downloading remote files, use the Smbfile object to read remote files, the code is as follows:

[Java]View Plaincopy print?
  1. InputStream in = null;
  2. Bytearrayoutputstream out = null;
  3. try {
  4. //Create remote file Object
  5. String Remotephotourl = "Smb://share:[email protected]/sharedfolder/test.jpg";
  6. Smbfile remotefile = new Smbfile (Remotephotourl);
  7. Remotefile.connect (); //try to connect
  8. //Create a file stream
  9. in = new Bufferedinputstream (new Smbfileinputstream (RemoteFile));
  10. out = new Bytearrayoutputstream ((int) remotefile.length ());
  11. //Read file contents
  12. byte[] buffer = new byte[4096];
  13. int len = 0; //Read length
  14. While (len = in.read (buffer, 0, buffer.length))! =- 1) {
  15. Out.write (buffer, 0, Len);
  16. }
  17. Out.flush (); //Refresh buffered output stream
  18. return Out.tobytearray ();
  19. }
  20. catch (Exception e) {
  21. String msg = "Error downloading remote file:" + e.getlocalizedmessage ();
  22. SYSTEM.OUT.PRINTLN (msg);
  23. }
  24. finally {
  25. try {
  26. if (out! = null) {
  27. Out.close ();
  28. }
  29. if (in = null) {
  30. In.close ();
  31. }
  32. }
  33. catch (Exception e) {}
  34. }
        InputStream in = null;        Bytearrayoutputstream out = null;             try {//Create remote file object String remotephotourl = "Smb://share:[email protected]/sharedfolder/test.jpg";            Smbfile remotefile = new Smbfile (Remotephotourl); Remotefile.connect ();            Attempt to connect//create file stream in = new Bufferedinputstream (new Smbfileinputstream (RemoteFile));            out = new Bytearrayoutputstream ((int) remotefile.length ());            Read file contents 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 ();        Refreshes the buffered output stream return Out.tobytearray ();            } catch (Exception e) {String msg = "Error downloading remote file:" + e.getlocalizedmessage ();        SYSTEM.OUT.PRINTLN (msg); } finally {try {if (out! = null) {out.clOSE ();                } if (in = null) {in.close (); }} catch (Exception e) {}}

Java reads and writes Windows shared folders.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.