Java列出本地文件列表并下载文件
这个很简单,使用java的file类即可实现,核心代码如下:
public class FileUtil {
public static List<FileVO> getFileVOList(String pathName) throws IOException {
File rootFile = new File(pathName);
List<FileVO> fileVOList = new ArrayList<FileVO>();
CustomQueue<FileVO> file_queue = new CustomQueue<FileVO>(); // 构建一个队列
FileVO rootFileVO = new FileVO();
rootFileVO.setName(rootFile.getName());
rootFileVO.setFile(rootFile);
rootFileVO.setProxyPath("/");
File[] list = null;
if (rootFile.exists()) {
list = rootFile.listFiles();
return fileVOList;
}
for (File file : list) { // 遍历顶级目录
FileVO topFileVO = new FileVO();
topFileVO.setName(file.getName());
topFileVO.setpId(rootFileVO.getId());
topFileVO.setFile(file);
topFileVO.setProxyPath(rootFileVO.getProxyPath() + file.getName());
fileVOList.add(topFileVO);
if (file.isDirectory()) {
file_queue.add(topFileVO);
}
while (!file_queue.isNull()) { // 从二级子目录开始,逐层遍历
FileVO subdirs = file_queue.get(); // 先取得二级子目录名称
File[] subFiles = subdirs.getFile().listFiles();
for (File subdir : subFiles) { // 遍历每个下一级子目录
FileVO subFileVO = new FileVO();
subFileVO.setName(subdir.getName());
subFileVO.setpId(subdirs.getId());
subFileVO.setFile(subdir);
subFileVO.setProxyPath(subdirs.getProxyPath() + "/" + subdir.getName());
fileVOList.add(subFileVO);
if (subdir.isDirectory()) {
file_queue.add(subFileVO); // 如果内层还有子目录,添加到队列中
}
}
}
}
return fileVOList;
}
public static byte[] getBytes(String filePath){
byte[] buffer = null;
try {
File file = new File(filePath);
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
IOUtils.copyLarge(fis, bos);
/*byte[] b = new byte[1000];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
} */
fis.close();
bos.close();
buffer = bos.toByteArray();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return buffer;
}
public static void writeFile(String filePath ,OutputStream out){
FileInputStream input = null;
try {
input = new FileInputStream(filePath);
BufferedInputStream in = new BufferedInputStream(input);
int len = 0;
byte[] b = new byte[1024];
while ((len = in.read(b)) > 0) {
out.write(b, 0, len);
}
out.flush();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
try {
if (out != null) {
out.close();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
Java获得ftp服务器文件列表并下载文件
这个需要用到apache的commons-net包,核心代码如下:
public class FtpFileUtil {
private FTPClient ftp;
/**
* 重载构造函数
* @param isPrintCommmand 是否打印与FTPServer的交互命令
*/
public FtpFileUtil(boolean isPrintCommmand){
ftp = new FTPClient();
if(isPrintCommmand){
ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
}
}
/**
* 登陆FTP服务器
* @param host FTPServer IP地址
* @param port FTPServer 端口
* @param username FTPServer 登陆用户名
* @param password FTPServer 登陆密码
* @return 是否登录成功
* @throws IOException
*/
public boolean login(String host,int port,String username,String password) throws IOException{
this.ftp.connect(host,port);
if(FTPReply.isPositiveCompletion(this.ftp.getReplyCode())){
if(this.ftp.login(username, password)){
this.ftp.setControlEncoding("GBK");
this.ftp.enterLocalPassiveMode();
return true;
}
}
if(this.ftp.isConnected()){
this.ftp.disconnect();
}
return false;
}
/**
* 关闭数据链接
* @throws IOException
*/
public void disConnection() throws IOException{
if(this.ftp.isConnected()){
this.ftp.disconnect();
}
}
public byte[] getByte(String pathName)throws IOException{
byte[] buffer = null;
if (!pathName.endsWith("/")) {
String directory = StringUtils.substringBeforeLast(pathName, "/")+"/";
String fileName = StringUtils.substringAfterLast(pathName, "/");
this.ftp.changeWorkingDirectory(directory);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
// InputStream ins = this.ftp.retrieveFileStream(fileName);
// IOUtils.copyLarge(ins, bos);
this.ftp.retrieveFile(fileName, bos);
buffer = bos.toByteArray();
// ins.close();
bos.close();
}
return buffer;
}
public List<FtpFileVO> getFileVOList(String pathName)throws IOException{
List<FtpFileVO> fileVOList = new ArrayList<FtpFileVO>();
CustomQueue<FtpFileVO> file_queue = new CustomQueue<FtpFileVO>(); // 构建一个队列
if(pathName.startsWith("/")&&pathName.endsWith("/")){
String directory = pathName;
//更换目录到当前目录
this.ftp.changeWorkingDirectory(directory);
FtpFileVO rootFileVO = new FtpFileVO();
rootFileVO.setProxyPath("/");
rootFileVO.setPath(pathName);
FTPFile[] list = this.ftp.listFiles();
for (FTPFile file : list) { // 遍历顶级目录
FtpFileVO topFileVO = new FtpFileVO();
topFileVO.setName(file.getName());
topFileVO.setpId(rootFileVO.getId());
topFileVO.setProxyPath(rootFileVO.getProxyPath() + file.getName());
topFileVO.setPath(pathName+file.getName()+"/");
fileVOList.add(topFileVO);
if (file.isDirectory()) {
file_queue.add(topFileVO);
}
while (!file_queue.isNull()) { // 从二级子目录开始,逐层遍历
FtpFileVO subdirs = file_queue.get(); // 先取得二级子目录名称
this.ftp.changeWorkingDirectory(subdirs.getPath());
FTPFile[] subFiles = this.ftp.listFiles();
for (FTPFile subdir : subFiles) { // 遍历每个下一级子目录
FtpFileVO subFileVO = new FtpFileVO();
subFileVO.setName(subdir.getName());
subFileVO.setpId(subdirs.getId());
subFileVO.setProxyPath(subdirs.getProxyPath() + "/" + subdir.getName());
subFileVO.setPath(subdirs.getPath()+subdir.getName()+"/");
fileVOList.add(subFileVO);
if (subdir.isDirectory()) {
file_queue.add(subFileVO); // 如果内层还有子目录,添加到队列中
}
}
}
}
}
return fileVOList;
}
}
操作时,要记得登入和登出
Java下载sftp服务器上文件并下载
这个需要使用到jcraft的jsch包,核心代码如下:
public class SftpFileUtil {
private static Logger log = Logger.getLogger(SftpFileUtil.class.getName());
private ChannelSftp sftp;
private Session sshSession = null;
/**
* 通过SFTP连接服务器
*/
public void connect(String host,int port,String username,String password)
{
try
{
JSch jsch = new JSch();
jsch.getSession(username, host, port);
sshSession = jsch.getSession(username, host, port);
if (log.isInfoEnabled())
{
log.info("Session created.");
}
sshSession.setPassword(password);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshConfig.put("userauth.gssapi-with-mic", "no");
sshSession.setConfig(sshConfig);
sshSession.connect();
if (log.isInfoEnabled())
{
log.info("Session connected.");
}
Channel channel = sshSession.openChannel("sftp");
channel.connect();
if (log.isInfoEnabled())
{
log.info("Opening Channel.");
}
sftp = (ChannelSftp) channel;
if (log.isInfoEnabled())
{
log.info("Connected to " + host + ".");
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* 关闭连接
*/
public void disconnect()
{
if (this.sftp != null)
{
if (this.sftp.isConnected())
{
this.sftp.disconnect();
if (log.isInfoEnabled())
{
log.info("sftp is closed already");
}
}
}
if (this.sshSession != null)
{
if (this.sshSession.isConnected())
{
this.sshSession.disconnect();
if (log.isInfoEnabled())
{
log.info("sshSession is closed already");
}
}
}
}
public byte[] getByte(String pathName)throws IOException, SftpException{
byte[] buffer = null;
if (!pathName.endsWith("/")) {
String directory = StringUtils.substringBeforeLast(pathName, "/")+"/";
String fileName = StringUtils.substringAfterLast(pathName, "/");
this.sftp.cd(directory);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
InputStream ins = this.sftp.get(fileName);
IOUtils.copyLarge(ins, bos);
buffer = bos.toByteArray();
ins.close();
bos.close();
}
return buffer;
}
public List<SftpFileVO> getFileVOList(String pathName)throws IOException, SftpException{
List<SftpFileVO> fileVOList = new ArrayList<SftpFileVO>();
CustomQueue<SftpFileVO> file_queue = new CustomQueue<SftpFileVO>(); // 构建一个队列
if(pathName.startsWith("/")&&pathName.endsWith("/")){
//更换目录到当前目录
SftpFileVO rootFileVO = new SftpFileVO();
rootFileVO.setProxyPath("/");
rootFileVO.setPath(pathName);
Vector<LsEntry> list = this.sftp.ls(pathName);
for (LsEntry file : list) {
// 遍历顶级目录
if (!file.getFilename().equals(".")&&!file.getFilename().equals("..")) {
SftpFileVO topFileVO = new SftpFileVO();
topFileVO.setName(file.getFilename());
topFileVO.setpId(rootFileVO.getId());
topFileVO.setPath(pathName+file.getFilename()+"/");
topFileVO.setProxyPath(rootFileVO.getProxyPath() + file.getFilename());
fileVOList.add(topFileVO);
SftpATTRS attrs = this.sftp.stat(pathName+file.getFilename());
if (attrs.isDir()) {
file_queue.add(topFileVO);
}
while (!file_queue.isNull()) { // 从二级子目录开始,逐层遍历
SftpFileVO subdirs = file_queue.get(); // 先取得二级子目录名称
Vector<LsEntry> subFiles = this.sftp.ls(subdirs.getPath());
for (LsEntry subdir : subFiles) {
// 遍历每个下一级子目录
if (!subdir.getFilename().equals(".")&&!subdir.getFilename().equals("..")) {
SftpFileVO subFileVO = new SftpFileVO();
subFileVO.setName(subdir.getFilename());
subFileVO.setpId(subdirs.getId());
subFileVO.setProxyPath(subdirs.getProxyPath() + "/" + subdir.getFilename());
subFileVO.setPath(subdirs.getPath()+subdir.getFilename()+"/");
fileVOList.add(subFileVO);
SftpATTRS attrs2 = this.sftp.stat(subdirs.getPath()+subdir.getFilename());
if (attrs2.isDir()) {
file_queue.add(subFileVO); // 如果内层还有子目录,添加到队列中
}
}
}
}
}
}
}
return fileVOList;
}
}
这里需要注意登入登出
Java列出samba服务器上文件夹列表并下载文件
这个需要用到jcifs,核心代码如下:
public class SmbFileUtil {
public NtlmPasswordAuthentication authentication ;
public boolean isAuth;
public String prefix;
public SmbFileUtil(boolean isAuth,String address,String publicDir) {
this.isAuth = isAuth;
this.prefix = "smb://"+address+"/"+publicDir;
}
public byte[] getByte(String pathName) throws IOException{
byte[] buffer = null;
if (!pathName.endsWith("/")) {
SmbFile file = getFile(pathName);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
InputStream ins = file.getInputStream();
if (file.isFile()) {
IOUtils.copyLarge(ins, bos);
}
buffer = bos.toByteArray();
ins.close();
bos.close();
}
return buffer;
}
public void login(String userName,String passWord){
this.authentication = new NtlmPasswordAuthentication("", userName, passWord);
}
public SmbFile getFile(String pathName) throws MalformedURLException{
if (isAuth) {
return new SmbFile(this.prefix+pathName, authentication);
}else {
return new SmbFile(this.prefix+pathName);
}
}
public List<SmbFileVO> getFileVOList(String pathName) throws MalformedURLException, SmbException{
List<SmbFileVO> fileVOList = new ArrayList<SmbFileVO>();
CustomQueue<SmbFileVO> file_queue = new CustomQueue<SmbFileVO>(); // 构建一个队列
SmbFile rootFile = getFile(pathName);
SmbFileVO rootFileVO = new SmbFileVO();
rootFileVO.setName(StringUtils.remove(rootFile.getName(), "/"));
rootFileVO.setFile(rootFile);
rootFileVO.setProxyPath("/");
SmbFile[] list = rootFile.listFiles();
for (SmbFile file : list) { // 遍历顶级目录
SmbFileVO topFileVO = new SmbFileVO();
topFileVO.setName(StringUtils.remove(file.getName(), "/"));
topFileVO.setpId(rootFileVO.getId());
topFileVO.setFile(file);
topFileVO.setProxyPath(rootFileVO.getProxyPath() + StringUtils.remove(file.getName(), "/"));
fileVOList.add(topFileVO);
if (file.isDirectory()) {
file_queue.add(topFileVO);
}
while (!file_queue.isNull()) { // 从二级子目录开始,逐层遍历
SmbFileVO subdirs = file_queue.get(); // 先取得二级子目录名称
SmbFile[] subFiles = subdirs.getFile().listFiles();
for (SmbFile subdir : subFiles) { // 遍历每个下一级子目录
SmbFileVO subFileVO = new SmbFileVO();
subFileVO.setName(StringUtils.remove(subdir.getName(), "/"));
subFileVO.setpId(subdirs.getId());
subFileVO.setFile(subdir);
subFileVO.setProxyPath(subdirs.getProxyPath() + "/" + StringUtils.remove(subdir.getName(), "/"));
fileVOList.add(subFileVO);
if (subdir.isDirectory()) {
file_queue.add(subFileVO); // 如果内层还有子目录,添加到队列中
}
}
}
}
return fileVOList;
}
}