Apache commons VFS之Shell源代码示例

这个示例主要是模拟一个Shell程序,通过输入一些命令,执行操作。源代码来自官网。

这个示例的特点:

1.       接收用户的输入;

2.       通过字符解析和判断;

3.       利用VFS自带的一些功能进行功能实现;

package test.ffm83.commons.VFS;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.text.DateFormat;

import java.util.ArrayList;

import java.util.Date;

import java.util.StringTokenizer;

import org.apache.commons.vfs2.FileContent;

import org.apache.commons.vfs2.FileObject;

import org.apache.commons.vfs2.FileSystemException;

import org.apache.commons.vfs2.FileSystemManager;

import org.apache.commons.vfs2.FileType;

import org.apache.commons.vfs2.FileUtil;

import org.apache.commons.vfs2.Selectors;

import org.apache.commons.vfs2.VFS;

/**

* A simple command-line shell for performing file operations.

* @author <a
href="mailto:adammurdoch@apache.org">AdamMurdoch</a>

* @author
Gary D. Gregory,范芳铭整理和添加注释

*/

public
class
Shell

{

private
static final
String CVS_ID =
"$Id:Shell.java 232419 2005-08-13 07:23:40 +0200(Sa, 13 Aug 2005) imario $";

private
final
FileSystemManager mgr;

privateFileObject
cwd;

privateBufferedReader
reader;

public
static void
main(final String[] args)

{

try

{

(new Shell()).go();

}

catch (Exception e)

{

e.printStackTrace();

System.exit(1);

}

System.exit(0);

}

privateShell()
throwsFileSystemException

{

mgr = VFS.getManager();

cwd =
mgr.resolveFile(System.getProperty("user.dir"));//获取当前文件夹

reader = new BufferedReader(new InputStreamReader(System.in));//接收输入内容

}

private
void
go() throws Exception

{

System.out.println("VFS Shell [" +
CVS_ID +
"]");

while (true)

{

final String[] cmd = nextCommand();

if (cmd ==
null)

{

return;

}

if (cmd.length == 0)

{

continue;

}

final String cmdName = cmd[0];

if (cmdName.equalsIgnoreCase("exit") ||cmdName.equalsIgnoreCase("quit"))

{

return;

}

try

{

handleCommand(cmd);

}

catch (final Exception e)

{

System.err.println("Command failed:");

e.printStackTrace(System.err);

}

}

}

/**

* Handles a command.

*/

private
void
handleCommand(final String[] cmd)
throws Exception

{

final String cmdName = cmd[0];

if (cmdName.equalsIgnoreCase("cat"))

{

cat(cmd);

}

else
if
(cmdName.equalsIgnoreCase("cd"))

{

cd(cmd);

}

else
if
(cmdName.equalsIgnoreCase("cp"))

{

cp(cmd);

}

else
if
(cmdName.equalsIgnoreCase("help"))

{

help();

}

else
if
(cmdName.equalsIgnoreCase("ls"))

{

ls(cmd);

}

else
if
(cmdName.equalsIgnoreCase("pwd"))

{

pwd();

}

else
if
(cmdName.equalsIgnoreCase("rm"))

{

rm(cmd);

}

else
if
(cmdName.equalsIgnoreCase("touch"))

{

touch(cmd);

}

else

{

System.err.println("Unknown command \""+ cmdName +
"\".");

}

}

/**

* Does a ‘help‘ command.

*/

private
void
help()

{

System.out.println("Commands:");

System.out.println("cat <file>        Displays the contents of a file.");

System.out.println("cd [folder]        Changescurrent folder.");

System.out.println("cp <src> <dest>   Copies a file or folder.");

System.out.println("help               Shows thismessage.");

System.out.println("ls [-R] [path]     Listscontents of a file or folder.");

System.out.println("pwd                Displayscurrent folder.");

System.out.println("rm <path>         Deletes a file or folder.");

System.out.println("touch <path>       Setsthe last-modified time of a file.");

System.out.println("exit       Exits thisprogram.");

System.out.println("quit       Exits thisprogram.");

}

/**

* Does an ‘rm‘ command.

*/

private
void
rm(final String[] cmd)
throws Exception

{

if (cmd.length < 2)

{

throw
new
Exception("USAGE: rm <path>");

}

final FileObject file =
mgr.resolveFile(cwd, cmd[1]);

file.delete(Selectors.SELECT_SELF);

}

/**

* Does a ‘cp‘ command.

*/

private
void
cp(final String[] cmd)
throws Exception

{

if (cmd.length < 3)

{

throw
new
Exception("USAGE: cp <src><dest>");

}

final FileObject src =
mgr.resolveFile(cwd, cmd[1]);

FileObject dest = mgr.resolveFile(cwd, cmd[2]);

if (dest.exists() && dest.getType() ==FileType.FOLDER)

{

dest =dest.resolveFile(src.getName().getBaseName());

}

dest.copyFrom(src, Selectors.SELECT_ALL);

}

/**

* Does a ‘cat‘ command.

*/

private
void
cat(final String[] cmd)
throws Exception

{

if (cmd.length < 2)

{

throw
new
Exception("USAGE: cat<path>");

}

// Locate the file

final FileObject file =
mgr.resolveFile(cwd, cmd[1]);

// Dump the contents to System.out

FileUtil.writeContent(file,System.out);

System.out.println();

}

/**

* Does a ‘pwd‘ command.

*/

private
void
pwd()

{

System.out.println("Current folder is " +
cwd.getName());

}

/**

* Does a ‘cd‘ command.

* If the taget directory does notexist, a message is printed to
<code>System.err</code>.

*/

private
void
cd(final String[] cmd)
throws Exception

{

final String path;

if (cmd.length > 1)

{

path = cmd[1];

}

else

{

path = System.getProperty("user.home");

}

// Locate and validate the folder

FileObject tmp = mgr.resolveFile(cwd, path);

if (tmp.exists())

{

cwd = tmp;

}

else

{

System.out.println("Folder does not exist: "+ tmp.getName());

}

System.out.println("Current folder is " +
cwd.getName());

}

/**

* Does an ‘ls‘ command.

*/

private
void
ls(final String[] cmd)
throws FileSystemException

{

int pos = 1;

final
boolean
recursive;

if (cmd.length > pos && cmd[pos].equals("-R"))

{

recursive = true;

pos++;

}

else

{

recursive = false;

}

final FileObject file;

if (cmd.length > pos)

{

file = mgr.resolveFile(cwd, cmd[pos]);

}

else

{

file = cwd;

}

if (file.getType() == FileType.FOLDER)

{

// List the contents

System.out.println("Contents of " + file.getName());

listChildren(file, recursive,
"");

}

else

{

// Stat the file

System.out.println(file.getName());

final FileContent content = file.getContent();

System.out.println("Size: " + content.getSize() +
" bytes.");

final DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);

final String lastMod = dateFormat.format(newDate(content.getLastModifiedTime()));

System.out.println("Last modified: " + lastMod);

}

}

/**

* Does a ‘touch‘ command.

*/

private
void
touch(final String[] cmd)
throws Exception

{

if (cmd.length < 2)

{

throw
new
Exception("USAGE: touch<path>");

}

final FileObject file =
mgr.resolveFile(cwd, cmd[1]);

if (!file.exists())

{

file.createFile();

}

file.getContent().setLastModifiedTime(System.currentTimeMillis());

}

/**

* Lists the children of a folder.

*/

private
void
listChildren(final FileObject dir,

final
boolean
recursive,

final String prefix)

throws FileSystemException

{

final FileObject[] children = dir.getChildren();

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

{

final FileObject child = children[i];

System.out.print(prefix);

System.out.print(child.getName().getBaseName());

if (child.getType() == FileType.FOLDER)

{

System.out.println("/");

if (recursive)

{

listChildren(child,recursive, prefix +
"    ");

}

}

else

{

System.out.println();

}

}

}

/**

* Returns the next command, split intotokens.

*/

privateString[] nextCommand()
throws IOException

{

System.out.print("> ");

final String line =
reader.readLine();

if (line ==
null)

{

return
null
;

}

final ArrayList<String> cmd =
newArrayList<String>();

final StringTokenizer tokens =
new StringTokenizer(line);

while (tokens.hasMoreTokens())

{

cmd.add(tokens.nextToken());

}

return cmd.toArray(new String[cmd.size()]);

}

}

运行结果如下:

VFS Shell [$Id:Shell.java 2324192005-08-13 07:23:40 +0200 (Sa, 13 Aug 2005) imario $]

> pwd

Current folder isfile:///D:/develop/eclipse/Workspaces/test_all

时间: 2024-07-30 21:10:59

Apache commons VFS之Shell源代码示例的相关文章

Apache commons VFS 文件操作 源代码示例

通过VFS对文件进行一些操作,包括写入.读取文件,判断文件是否可读可写等示例.Apache commons VFS包和apache commons的其他基础性类有非常密切的关系. 整理了一些常用的方法,源代码如下: package test.ffm83.commons.VFS; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.O

Apache commons VFS简介和ShowProperties源代码示例

Apache commons VFS又叫做 Apache Commons Virtual FileSystem.是一组功能强大的对各类资源的访问接口,目前这个JAR包得到了全新的重构,目前最新的版本是2.2. 如果我们在平常的工作中,需要得到一些不同格式文件的信息,比如文件大小.所在路径.文件最后更改时间等,或者我们需要对文件进行一些常规的操作,比如删除文件,拷贝文件等等,那么Apache Commons中的VFS(Virtual File System)就是我们可以考虑的一个开源系统. 据VF

Maven+Spring Batch+Apache Commons VF学习

Apache Commons VFS资料:例子:http://www.zihou.me/html/2011/04/12/3377.html详细例子:http://p7engqingyang.iteye.com/blog/1702429 Apache Commons VFS:文件系统工具,对不来自与不同的文件系统的文件进行操作,可以处理非本地文件(vfs中,原来存在ftp有时候不能正常关闭的情况,commons-vfs2 出了以后,该问题已经得到解决 )VFS为访问各种不同的文件系统提供了单一的应

Apache Commons CLI 开发命令行工具示例

概念说明Apache Commons CLI 简介 虽然各种人机交互技术飞速发展,但最传统的命令行模式依然被广泛应用于各个领域:从编译代码到系统管理,命令行因其简洁高效而备受宠爱.各种工具和系统都 提供了详尽的使用手册,有些还提供示例说明如何二次开发.然而关于如何开发一个易用.强壮的命令行工具的文章却很少.本文将结合 Apache Commons CLI,通过一个完整的例子展示如何准备.开发.测试一个命令行工具.希望本文对有相关需求的读者能有所帮助.      Apache Commons CL

使用 Apache Commons CLI 开发命令行工具示例

概念说明 Apache Commons CLI 简介 Apache Commons CLI 是 Apache 下面的一个解析命令行输入的工具包,该工具包还提供了自动生成输出帮助文档的功能. Apache Commons CLI 支持多种输入参数格式,主要支持的格式有以下几种: POSIX(Portable Operating System Interface of Unix)中的参数形式,例如 tar -zxvf foo.tar.gz GNU 中的长参数形式,例如 du --human-read

Apache Commons 工具集

一.Commons BeanUtils http://jakarta.apache.org/commons/beanutils/index.html 说明:针对Bean的一个工具集.由于Bean往往是有一堆get和set组成,所以BeanUtils也是在此基础上进行一些包装. 使用示例:功能有很多,网站上有详细介绍.一个比较常用的功能是Bean Copy,也就是copy bean的属性.如果做分层架构开发的话就会用到,比如从PO(Persistent Object)拷贝数据到VO(Value O

一篇关于apache commons类库的详解

原文 http://blog.csdn.net/wiker_yong/article/details/23551209 1.1. 开篇 在Java的世界,有很多(成千上万)开源的框架,有成功的,也有不那么成功的,有声名显赫的,也有默默无闻的.在我看来,成功而默默无闻的那些框架值得我们格外的尊敬和关注,Jakarta Commons就是这样的一个框架.如果你至少参与了一个中型规模的Java项目,那么我想有超过一大半的机会你都接触和使用到了Jakarta Commons,不管你自己有没有察觉.就我所

编写更少量的代码:使用apache commons工具类库

Commons-configuration   Commons-FileUpload   Commons DbUtils   Commons BeanUtils  Commons CLI  Commons Codec   Commons Collections Commons DBCP    Commons HttpClient  Commons IO  Commons JXPath   Commons Lang   Commons Math   Commons Net   Commons Va

Apache Commons

官方链接走起 http://commons.apache.org/ Apache Commons包含了很多开源的工具,用于解决平时编程经常会遇到的问题,减少重复劳动.我选了一些比较常用的项目做简单介绍.文中用了很多网上现成的东西,我只是做了一个汇总整理. Commons BeanUtils http://jakarta.apache.org/commons/beanutils/index.html 说明:针对Bean的一个工具集.由于Bean往往是有一堆get和set组成,所以BeanUtils