判断两个文件是不是同一个文件 import java.io.File; import java.io.FileInputStream; public class InputStream2 { public static void main(String[] args) { //调用下面的方法 //判断两个文件是否相同 System.out.println
判断两个文件是不是同一个文件
import java.io.File;import java.io.FileInputStream;
public class InputStream2 {
public static void main(String[] args) {
//调用下面的方法
//判断两个文件是否相同
System.out.println(isSame("d:/ac/1.jpg", "d:/ac/a.txt"));
}
public static boolean isSame(String src, String dst) {
return isSame(new File(src) , new File(dst));
}
public static boolean isSame(File src, File dst) {
boolean result = false;
if (src.length() == dst.length()) { //如果两个文件的长度相同
try (var issrc = new FileInputStream(src); var isdst = new FileInputStream(dst)) {//读取两个文件
int num = 0;
while (issrc.read() == isdst.read()) {//两个文件的字节相等
num++; //循环次数
if (num == src.length()) {//判断循环次数是否与文件的字节相同(相同时代表文件读取完)
result = true;
break;
}
}
} catch (Exception e) {
}
}
return false;
}
}
FileInputStream输入流使用(读取文件)
import java.io.FileInputStream;import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
public class InputStream1 {
public static void main(String[] args) {
try(FileInputStream fis = new FileInputStream("d:/ac/1.jpg") ) {
byte[] bytes = new byte[10];
fis.skip(fis.available());//跳过所有可读的字节数据,
int len = fis.read(bytes);
System.out.println(Arrays.toString(bytes));
//[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
System.out.println(len);//-1 没有数据 读完
fis.skip(fis.available()-5);//跳过前五个字节,读取后五个字节
int len2 = fis.read(bytes);
System.out.println(Arrays.toString(bytes));
//[99, 2, -113, -1, -39, 0, 0, 0, 0, 0]
System.out.println(len2);//5
}
catch (Exception e){
}
//读取文件
try(FileInputStream fis = new FileInputStream("d:/ac/1.jpg") ) {
for( int i = 0; i < 10; i++ ) {
int t = fis.read();//读取一个字节,一个一个读,连读10次
System.out.printf("%03d ",t);
}
}catch (Exception e){
}
System.out.println();
try(FileInputStream fis = new FileInputStream("d:/ac/a.txt")) {
for( int i = 0; i < 10; i++ ) {
int t = fis.read();
System.out.printf("%03d ",t);
}
} catch (IOException e) {
}
//实现文件复制
//FileInputStream 读取 FileOutputStream 写入
try(var a = new FileInputStream("d:/ac/1.jpg"); var b = new FileOutputStream("d:/ac/11.jpg")) {
int len = 0;
while ((len = a.read()) !=-1){
b.write(len);
}
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}