public class File {
//远程文件的路径 username:password@server/path
//如admin:1@192.168.100.251/share/test.txt
private String path;
//获取远程文件的路径
public String getPath() {
return path;
}
//设置远程文件的路径
public void setPath(String path) {
this.path = path;
}
//构造方法
public File(String path) {
this.setPath(path);
};
//获得远程文件的内容的字符串形式
public String getString() throws YssException{
StringBuffer str=new StringBuffer();
String Path=this.getPath();
try {
SmbFile file=this.getFile(Path);
if(file.exists()&&file.isFile())
{
SmbFileInputStream ins=new SmbFileInputStream(file);
int length=file.getContentLength();
byte [] buffer=new byte[length];
while(ins.read(buffer)!=-1){
str.append(new String(buffer));
}
ins.close();
}
else
throw new YssException("此文件不存在或不是文件");
} catch (MalformedURLException e) {
throw new YssException("远程文件路径格式不正确,具体原因"+e.getMessage());
} catch (SmbException e) {
throw new YssException("远程文件访问错误,具体原因"+e.getMessage());
} catch (UnknownHostException e) {
throw new YssException("不能被发现的主机错误,具体原因"+e.getMessage());
} catch (IOException e) {
throw new YssException("远程文件读取错误,具体原因"+e.getMessage());
}
return str.toString();
}
//获得远程文件的内容的字节形式
public byte [] getBytes() throws YssException{
byte [] bytes=null;
String Path=this.getPath();
try {
SmbFile file=this.getFile(Path);
if(file.exists()&&file.isFile())
{
SmbFileInputStream ins=new SmbFileInputStream(file);
int length=file.getContentLength();
byte [] buffer=new byte[length];
while(ins.read(buffer)!=-1){
bytes=buffer;
}
ins.close();
}
else
throw new YssException("此文件不存在或不是文件,具体原因");
} catch (MalformedURLException e) {
throw new YssException("远程文件路径格式不正确,具体原因"+e.getMessage());
} catch (SmbException e) {
throw new YssException("远程文件访问错误,具体原因"+e.getMessage());
} catch (UnknownHostException e) {
throw new YssException("不能被发现的主机错误,具体原因"+e.getMessage());
} catch (IOException e) {
throw new YssException("远程文件读取错误,具体原因"+e.getMessage());
}
return bytes;
}
//删除文件或目录
public void delete() throws YssException{
SmbFile file=getFile(this.getPath());
try {
if(file.exists()){
file.delete();
}
} catch (SmbException e) {
throw new YssException("删除文件或目录时出现错误,具体信息"+e.getMessage());
}
}
//获得远程文件的长度
public int getLength() throws YssException{
return this.getFile(this.getPath()).getContentLength();
}
//测试是否是一个文件
public boolean isFile() throws YssException{
try {
return this.getFile(this.getPath()).isFile();
} catch (SmbException e) {
throw new YssException("出现错误,具体信息"+e.getMessage());
}
}
//测试是否是一个目录
public boolean isDirectory() throws YssException{
try {
return this.getFile(this.getPath()).isDirectory();
} catch (SmbException e) {
throw new YssException("出现错误,具体信息"+e.getMessage());
}
}
//私有方法,用来获得远程文件
private SmbFile getFile(String remotePath) throws YssException {
SmbFile file = null;
try {
file = new SmbFile("smb://" + remotePath);
} catch (MalformedURLException e) {
throw new YssException("远程文件路径格式不正确,具体原因" + e.getMessage());
}
return file;
}
}