打印出不同的文件名 [英] Printing Out File Names that are Different

查看:79
本文介绍了打印出不同的文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码有效,逻辑也有效。但是,我想打印出两个文件夹中不相同的实际文件的名称,这些文件保存在 fileNames1 的数组中fileNames2 。我一直在寻找没有解决方案的答案。在离开Java一段时间后,我才回到Java的困境。任何帮助,将不胜感激。

My code below works and the logic works. However, I want to print out the names of the actual files that are not the same in both folders, which are held in the arrays of fileNames1 and fileNames2. I have been searching for the answer with no solution. I am just getting back into the groove with Java after being away form it a while. Any help would be appreciated.

import java.io.File;
import java.util.ArrayList;

public class nameCompare {

    public static void main(String[] args) {

        String path1 = "C:/Users/hoflerj/Desktop/test"; 
        String path2 = "C:/Users/hoflerj/Desktop/test2"; 

        File folder1 = new File(path1);
        File folder2 = new File(path2);

        File[] listOfFiles1 = folder1.listFiles(); 
        File[] listOfFiles2 = folder2.listFiles(); 

        ArrayList<String> fileNames1 = new ArrayList<String>();
        ArrayList<String> fileNames2 = new ArrayList<String>();

        for (int i = 0; i < listOfFiles1.length; i++) 
        {

            if (listOfFiles1[i].isFile()) 
            {
                fileNames1.add(listOfFiles1[i].getName());//wow
            }
        }

        for (int i = 0; i < listOfFiles2.length; i++) 
        {

            if (listOfFiles2[i].isFile()) 
            {
                fileNames2.add(listOfFiles2[i].getName());//seriously wow
            }
        }


        for ( int i = 0; i < 1; i++ )
        {
            if (fileNames1.equals(fileNames2) )
            { 
                System.out.println("Files names are the same");
            }

            else if (fileNames1 != fileNames2 )
            { 
                System.out.println("Files names are not equal");
            }
        }

    }

}


推荐答案

创建并填充了两个列表之后,请使用以下代码:-

After you've created and populated both the lists, use the following code :-

for(String fileName : fileNames1)
{
 if(!fileNames2.contains(fileName))
   {
     System.out.println(fileName + " is not in both");
   } 
 else
   {
     System.out.println(fileName + " is in both the lists");
   }
}

此代码的作用是每个<$ c第一个 ArrayList 中的$ c> fileName 会检查第二个 ArrayList 是否包含相同的内容文件名与否,并相应地打印输出。

What this code does is that for each fileName in the first ArrayList it checks if the second ArrayList contains the same file name or not, and prints the output accordingly.

这篇关于打印出不同的文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆