比较文件然后删除具有更大字符的文件

Compare files then delete the one with the greater characters

我java比较了两个不同的文件,但我希望它使用字符最多的文件并删除另一个文件。我不认为它应该按文件大小来考虑,因为只添加一个额外的字符可能会有相同大小的文件。对吗? 感谢任何帮助。

这是我的代码:

import java.io.*;  
import java.util.*;  


public class FileComp  
{  

 public static void main (String[] args) throws java.io.IOException  
{  

  BufferedReader br2 = new BufferedReader (new  
InputStreamReader(System.in));  

String str = ("compt1.txt");  

String str1 = ("compt2.txt"); 

String s1="";  
String s2="",s3="",s4="";  
String y="",z="";  


BufferedReader br = new BufferedReader (new FileReader (str));  
BufferedReader br1 = new BufferedReader (new FileReader (str1));  

while((z=br1.readLine())!=null)  
s3+=z;  

while((y=br.readLine())!=null)  
 s1+=y;  

System.out.println ();  


int numTokens = 0;  
StringTokenizer st = new StringTokenizer (s1);  
String[] a = new String[10000];  
for(int l=0;l<10000;l++)  
  {a[l]="";}  
int i=0;  
while (st.hasMoreTokens())  
  {  
    s2 = st.nextToken();  
      a[i]=s2;  
i++;  
        numTokens++;  
  }  

 int numTokens1 = 0;  
 StringTokenizer st1 = new StringTokenizer (s3);  
 String[] b = new String[10000];  
 for(int k=0;k<10000;k++)  
  {b[k]="";}  
 int j=0;  
 while (st1.hasMoreTokens())  
   {  
    s4 = st1.nextToken();  
    b[j]=s4;  
    j++;  
    numTokens1++;  
   }  


int x=0;  
  for(int m=0;m<a.length;m++)  
  {  
if(a[m].equals(b[m])){}  
else  
{  
 x++;  
System.out.println(a[m] + " -- " +b[m]);  
System.out.println();}  
  }  
  //////////////////////////////Change this:
System.out.println("Number of differences " + x);  
if(x>0){System.out.println("Files are not equal");}  
else{System.out.println("Files are equal. No difference found");}  
////////////////////////////////////
}  
}  

使用

File file = new File("File.txt");
long l = file.length();

您可以对文件使用 length() 方法,returns 以字节为单位的大小

每个字符都会占用一些内存。所以,文件大小不应该相同。