Java Access Linux shared directory NFS samba__linux

Source: Internet
Author: User
Tags getmessage parent directory

Note: Java Access to NFS directory is not easy,

The idea was converted, since the NFS service was never successfully accessed. Just simply manipulate the local mount point. Reads and writes files for a locally mounted path. This achieves the effect of operating an NFS shared directory.



A recent need to use Java access to the shared directory under Linux, to achieve file download and upload, since the Linux shared files are mainly in two ways, Samba and Nfs,samba are based on the Microsoft Smb/cifs Protocol, NFS Network file system (network File System) is another protocol. The configuration and implementation code for both of these approaches is as follows: (Configuration is done under Ubuntu)

One, Samba

(1) Configuration:

A) Create a shared directory: Mkdir/home/pirate/smbshare, chmod 777 Smbshare

b Install Samba, sudo apt-get install samba, sudo apt-get install Smbfs

c) Modify the Samba configuration file, sudo gedit/etc/samba/smb.conf, add the following line at the end of the file:

[Smbshare] #-----Share name, use this name for client access

Path =/home/pirate/smbshare

Available = yes

Browsealbe = yes

Public = yes

writable = yes

D Create a shared User: sudo useradd AAA

f) Reboot Samba, Sudo/etc/init.d/samba restart

(2) Java access

Java code

public void Downloadviashare (final string ip,final string user,final string password,final string <span style= "COLOR: # 000000 ">dir</SPAN>)

{

Logger.debug ("Share (SMB) download!");

String newdir = dir;

String url = "";

Smbfile [] filelist = null;

FileOutputStream fos = null;

Smbfileinputstream smbis = null;

byte [] buffer = new byte[8192];

int readbytes = 0;

int totalbytes = 0;

if (!dir.endswith ("/"))//directory must end with "/"

Newdir = dir+ "/";

url = "smb://" +user+ ":" +password+ "@" +ip+ "/" +NEWDIR;

Long starttime = System.currenttimemillis ();

try {

Smbfile Sharedir = new Smbfile (URL);

if (Sharedir.isdirectory ())

{

FileList = Sharedir.listfiles ();

for (int i=0;i<filelist.length;i++)

{

if (Filelist[i].isfile ())

{

Smbis = new Smbfileinputstream ((Smbfile) filelist[i]);

FOS = new FileOutputStream (New File (Tempdir+file.separator+filelist[i].getname ()));

while ((readbytes = smbis.read (buffer)) > 0)

{

Fos.write (buffer,0,readbytes);

TotalBytes + = Readbytes;

}

Smbis.close ();

Fos.close ();

Logger.debug (Filelist[i].getname () + "is downloaded!");

Try

{

Filelist[i].delete ();

}catch (smbauthexception smbae)

{

Logger.debug (Filelist[i].getname () + "can not be deleted." ");

}

}

}

Long endtime = System.currenttimemillis ();

Long Timetaken = Endtime-starttime;

Logger.debug (totalbytes + "bytes downloaded in" + timetaken/1000 + "seconds at" + ((totalbytes/1000)/Math.max (1, timetaken/1000)) + "kb/sec");

}

}catch (malformedurlexception Urle)

{

Logger.debug ("Incorrect URL format!");

}catch (Smbexception Smbe) {

Smbe.printstacktrace ();

Logger.debug (This.getclass (). GetName () + "| |" +smbe.getmessage ());

}catch (IOException IoE)

{

Ioe.printstacktrace ();

Logger.debug (This.getclass (). GetName () + "| |" +ioe.getmessage ());

}finally

{

Try

{

Smbis.close ();

Fos.close ();

}catch (Exception Smbe)

{

Logger.debug (This.getclass (). GetName () + "| |" +smbe.getmessage ());

}

}

}





Second, NFS

(1) configuration

A) Install NFS, sudo apt-get install Nfs-kernel-server

(b) Establishment of a shared directory: Mkdir/home/pirate/nfsshare

c) Edit configuration: sudo gedit/etc/exports, add the following line at the end:

/home/pirate/nfsshare * (Rw,sync,no_all_squash), meaning:

Shared directory allows access to the network segment (read and write permissions, data transmission, client permissions)

Other commonly used parameters for Ubuntu NFS are:

RO read-only access

RW read-Write access sync all data is written to share on request

Async NFS can respond to requests before data is written

Secure NFS is sent via a secure TCP/IP port under 1024

Insecure NFS is sent over 1024 ports

Wdelay If multiple users are writing to the NFS directory, group write (default)

No_wdelay If multiple users are writing to the NFS directory, write now and do not need this setting when using Async.

Hide does not share subdirectories in NFS shared directories

No_hide Share subdirectories for NFS directories

Subtree_check Force NFS to check the permissions of the parent directory (default) if you share a subdirectory such as/usr/bin

No_subtree_check and above, do not check parent directory permissions

All_squash the UID and GID of shared files map anonymous users anonymous, which is suitable for public directories.

No_all_squash preserves UID and GID for shared files (default)

Root_squash all requests for root users are mapped to the same permissions as anonymous users (default)

No_root_squas Root user has full administrative access to the root directory

Anonuid=xxx Specify the UID of anonymous users in server/etc/passwd files for NFS

Anongid=xxx Specify the GID for anonymous users in server/etc/passwd files for NFS

d Restart Nfs:sudo service portmap restart, sudo service nfs-kernel-server restart

e) test: SHOWMOUNT-E To see if there is a share of the directory

(2) Code

This piece of code, although very simple, but it cost me a lot of strength. The JDK itself does not have access to NFS, it can only use a third-party package, Google found that Java access to NFS applications rarely, unexpectedly found no usable examples, far less than samba, and only sun Webnfs available to access NFS, in http:// Yanfs.dev.java.net only one of the bulk source, packaged after the jar has no place, even the API documents are not. I also have to worry about the evil. Looking for it, the Sun's online documentation groped for a clue.

Java code

public void Downloadvianfs (final string ip,final string user,final string password,final string dir)

{

Logger.debug ("NFS download begin!");

try {

String url = "nfs://" +ip+ "/" +DIR;

XFile XF = new XFile (URL);

if (Xf.exists ())

{

Logger.debug ("URL is ok!");

}else

{

Logger.debug ("URL is bad!");

Return

}

Xfileextensionaccessor NFSX = (xfileextensionaccessor) xf.getextensionaccessor ();

if (!NFSX.LOGINPCNFSD (IP, user, password))

{

Logger.debug ("Login failed!"); Return

}

String [] filelist = Xf.list ();

XFile temp = null;

Long starttime = System.currenttimemillis ();

int Filesz = 0;

for (String file:filelist)

{

temp = new XFile (url+ "/" +file);

Xfileinputstream in = new Xfileinputstream (temp);

Xfileoutputstream out = new Xfileoutputstream (tempdir+file.separator+file);

int C;

byte[] buf = new byte[8196];

while ((c = In.read (BUF)) > 0) {

Filesz + = C;

Out.write (buf, 0, C);

}

Logger.debug (file + "is downloaded!");

In.close ();

Out.close ();

if (Temp.canwrite ())

{

Temp.delete ();

Logger.debug (file + "is deleted!");

}else

{

Logger.debug (file + "can not be delted!");

}

}

Long endtime = System.currenttimemillis ();

Long Timediff = Endtime-starttime;

int rate = (int) ((filesz/1000)/(timediff/1000.0));

Logger.debug (Filesz + "bytes copied @" + rate + "kb/sec");

}catch (IOException e) {

Logger.debug (e);

}

}

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.