Java nfs-clientパッケージに基づいてNFSプロトコルを実現linuxサーバに接続してファイルのアップロードとダウンロード操作のソースコードを行う
19749 ワード
依存の追加
コードの例
// https://mvnrepository.com/artifact/com.emc.ecs/nfs-client
compile group: 'com.emc.ecs', name: 'nfs-client', version: '1.0.3'
コードの例
package com.xl;
import com.emc.ecs.nfsclient.nfs.io.Nfs3File;
import com.emc.ecs.nfsclient.nfs.io.NfsFileInputStream;
import com.emc.ecs.nfsclient.nfs.io.NfsFileOutputStream;
import com.emc.ecs.nfsclient.nfs.nfs3.Nfs3;
import com.emc.ecs.nfsclient.rpc.CredentialUnix;
import java.io.*;
public class NfsTransferFile {
private static final String NFS_IP = "192.168.0.101";
private static final String NFS_DIR = "/data/nfs";
public static void main(String[] args) {
uploadFileToNfs();
//downLoadFileFromNfs();
}
// Nfs
public static void uploadFileToNfs() {
String localDir = "F:\\look\\look.txt";
InputStream inputStream = null;
OutputStream outputStream = null;
try {
//
File localFile = new File(localDir);
// , Nfs
String localFileName = localFile.getName();
Nfs3 nfs3 = new Nfs3(NFS_IP, NFS_DIR, new CredentialUnix(0, 0, null), 3);
// Nfs
Nfs3File NfsFile = new Nfs3File(nfs3, "/" + localFileName);
//
inputStream = new BufferedInputStream(new FileInputStream(localFile));
// Nfs ,
outputStream = new BufferedOutputStream(new NfsFileOutputStream(NfsFile));
//
byte[] buffer = new byte[1024];
while ((inputStream.read(buffer)) != -1) {
outputStream.write(buffer);
}
System.out.println(" !");
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (outputStream != null) {
outputStream.close();
}
if (inputStream != null) {
inputStream.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
// Nfs
public static void downLoadFileFromNfs() {
String NfsFileDir = "/look.txt";
String localDir = "F:\\look\\";
InputStream inputStream = null;
OutputStream outputStream = null;
try {
Nfs3 nfs3 = new Nfs3(NFS_IP, NFS_DIR, new CredentialUnix(0, 0, null), 3);
// Nfs
Nfs3File nfsFile = new Nfs3File(nfs3, NfsFileDir);
String localFileName = localDir + nfsFile.getName();
//
File localFile = new File(localFileName);
//
inputStream = new BufferedInputStream(new NfsFileInputStream(nfsFile));
// Nfs ,
outputStream = new BufferedOutputStream(new FileOutputStream(localFile));
//
byte[] buffer = new byte[1024];
while (inputStream.read(buffer) != -1) {
outputStream.write(buffer);
}
System.out.println(" !");
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (outputStream != null) {
outputStream.close();
}
if (inputStream != null) {
inputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}