通过对IO和GUI的学习,自己用SWT做了一个简单的模拟杀毒软件的小程序。通过这个小程序主要是进一步加深对硬盘上的文件进行遍历读取的过程。
我的设计思路是:定义了两个类,一个是BackServer类,是后台处理数据,实现对硬盘文件的遍历,和匹配。另一个类UI类,实现了UI窗口的创建和数据的输出工作。
实现代码如下:
①:后台处理类:
//引入的包
import java.io.File;
import org.eclipse.swt.widgets.Text;
public class KillBackServer {
//定义一个静态函数,用来实现对一盘文件的遍历
public static void fun(File f ,Text txt2,Text txt1)
{
if(f.isDirectory())
{
File file[] = f.listFiles();
try
{
for(int i = 0 ; i <file.length ; i++)
{
fun(file[i],txt2 , txt1);
}
}
catch(Exception e){}
}
else
{
if("我是病毒.exe".equals(f.getName())) //这里 我是病毒.exe 是自己创建的一个文件用来模拟病毒,大家可以修改成自己设置好的文件名称
{
txt2.insert(f.getPath()+" ");
//System.out.println(f);
f.delete();
txt2.insert("该病毒已被查杀\n");
//System.out.println("该病毒已被查杀");
}
txt1.insert(f.getPath()+"\n");
System.out.println(f.getPath());
}
}
}
②:创建的UI类:
//引入的包
import java.io.File;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
public class KillBoxUI {
public static void main(String args[])
{
//定义窗体
final Display display = Display.getDefault();
final Shell shell = new Shell();
shell.setSize(700, 500);
shell.setText("小小的杀毒程序");
//定义第一个text,显示遍历的文件地址
final Text txt1 = new Text(shell , SWT.MULTI);
txt1.setBounds(100, 50, 500, 20);
//定义第二个text,显示查杀结果
final Text txt2 = new Text(shell , SWT.MULTI);
txt2.setBounds(100, 100, 500, 150);
//定义一个数组,存放硬盘的盘符
final String str[] = {"C:\\","D:\\","E:\\","F:\\",};
//添加下拉菜单
final Combo combo = new Combo(shell , SWT.READ_ONLY);
combo.setBounds(100, 350, 100, 30);
combo.add(str[0]);
combo.add(str[1]);
combo.add(str[2]);
combo.add(str[3]);
combo.add("全盘扫描");
//添加按钮
final Button b = new Button(shell , SWT.NULL);
b.setBounds(540, 350, 60, 30);
b.setText("开始扫描");
//添加事件监听
b.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
if("全盘扫描".equals(combo.getText()))
{
for(int i = 0 ; i < str.length; i++)
{
File f = new File(str[i]);
KillBackServer.fun(f,txt2,txt1);
}
}
else
{
String str1 = combo.getText();
File f = new File(str1);
KillBackServer.fun(f,txt2,txt1);
}
txt2.insert("您的电脑很健康!");
}
});
shell.layout();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
}
}
运行结果如下:
初始界面如下: 点击下拉箭头后,选择盘符:
选择盘符后,点击开始扫描按钮,无毒的情况: 当有毒被查杀的时候(该病毒需要自己模拟创建“我是病毒.exe”):
有些效果需要在运行的时候才能发现,比如第一个动态的显示正在匹配的文件。截图显示的不是很好
后记:跟成熟的软件比起来,这段小程序还有很多的不足,不过用来体验原理过程还是挺不错的。回想整个过程,例如用数组存放盘符这个设计就不是特别合理,应该动态的读取电脑上到底有几个盘符,因为不同的电脑上有不同的盘符数。有很多诸如此类的不足和缺点,还希望各位大侠多多包涵
posted on 2010-11-02 19:58
Soap MacTavish 阅读(309)
评论(1) 编辑 收藏