java to determine whether the contents of two files are exactly the same

The article reprint url address is as follows:
http://blog.csdn.net/c_mihoo/article/details/16119523
 
  /**
	   * Determine whether the content of the two files is the same, the file name should use the absolute path
	   * @param fileName1 : absolute path to file 1
	   * @param fileName2 : absolute path to file 2
	   * @return returns true for the same, false for the same
	   */
	public boolean isSameFile(String fileName1,String fileName2){
		FileInputStream fis1 = null;
		FileInputStream fis2 = null;
		try {
			fis1 = new FileInputStream(fileName1);
			fis2 = new FileInputStream(fileName2);
			
			int len1 = fis1.available();//Return the total number of bytes
			int len2 = fis2.available();
			
			if (len1 == len2) {//The length is the same, then compare the specific content
				//create two byte buffers
				byte[] data1 = new byte[len1];
				byte[] data2 = new byte[len2];
				
				//Read the contents of the two files into the buffer respectively
				fis1.read(data1);
				fis2.read(data2);
				
				// Compare each byte in the file in turn
				for (int i=0; i<len1; i++) {
					//As long as one byte is different, the two files are different
					if (data1[i] != data2[i]) {
						System.out.println("The content of the file is different");
						return false;
					}
				}
				System.out.println("The two files are exactly the same");
				return true;
			} else {
				//The length is different, the file must be different
				return false;
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace ();
		} catch (IOException e) {
			e.printStackTrace ();
		} finally {//Close the file stream to prevent memory leaks
			if (fis1 != null) {
				try {
					fis1.close();
				} catch (IOException e) {
					//neglect
					e.printStackTrace ();
				}
			}
			if (fis2 != null) {
				try {
					fis2.close();
				} catch (IOException e) {
					//neglect
					e.printStackTrace ();
				}
			}
		}
		return false;
	}

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326636013&siteId=291194637