问题遇到的现象和发生背景
java.io.FileNotFoundException: C:\Users\xcj\Desktop\MalwareMD5.txt (文件名、目录名或卷标语法不正确。) 我是直接复制文本属性中绝对路径的,读取后缀为txt会出错。.exe就不会出错,手敲路径有时候能成功,有时候不能。
用代码块功能插入代码,请勿粘贴截图
import java.io.File;
import java.io.FileInputStream;
import java.security.MessageDigest;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class hello {
static char hexdigits[] = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
public static String getMD5(File file) { //获取文件的MD5码
FileInputStream fis = null;
try {
MessageDigest md = MessageDigest.getInstance("MD5");
fis = new FileInputStream(file);
byte[] buffer = new byte[2048];
int length = -1;
while((length =fis.read(buffer)) != -1) {
md.update(buffer, 0, length);
}
byte[] b =md.digest();
return byteToHexString(b); //将字节转化为字符返回
} catch(Exception ex) {
ex.printStackTrace();
return null;
} finally {
try {
fis.close();
}catch(Exception ex) {
ex.printStackTrace();
}
}
}
public static String byteToHexString(byte[] tmp) {
String s;
char str[] = new char[16*2];
int k=0;
for (int i=0; i<16; i++) {//将MD5每个字节转换为16进制字符
byte byte0 =tmp[i];
str[k++] = hexdigits[byte0>>>4 & 0xf];//取字节高4位的数字转换
str[k++] = hexdigits[byte0 & 0xf];//取字节低4位的数字转换
}
s=new String(str);
return s;
}
public static void compare(String t) //将待检查文件的MD5码于病毒代码库中内容做对比
{
File file = new File("C:\\Users\\xcj\\Desktop\\MalwareMD5.txt");
try (BufferedReader br = new BufferedReader(new FileReader(file)))//
{
String line;
while ((line = br.readLine()) != null) {//读取每行内容直到为空
System.out.println(line);
if(line == t)
{
System.out.println("匹配成功,此软件为病毒软件");
System.out.println(line);
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("经过对比,未发现病毒");
}
public static void main(String args[]) {
System.out.println("此文件MD5码为:");
System.out.println(getMD5(new File("D:\\QQ\\Bin\\QQScLauncher.exe")));
String t = getMD5(new File("D:\\QQ\\Bin\\QQScLauncher.exe"));
compare(t);
}
}
运行结果及报错内容
此文件MD5码为:
0b66b594e69d7074bac170ba707610d4
java.io.FileNotFoundException: C:\Users\xcj\Desktop\MalwareMD5.txt (文件名、目录名或卷标语法不正确。)
at java.base/java.io.FileInputStream.open0(Native Method)
at java.base/java.io.FileInputStream.open(FileInputStream.java:216)
at java.base/java.io.FileInputStream.(FileInputStream.java:157)
at java.base/java.io.FileReader.(FileReader.java:75)
at hello.compare(hello.java:59)
at hello.main(hello.java:82)
经过对比,未发现病毒
我的解答思路和尝试过的方法
将\\换成/