我有一个应用程序,用户在其中选择特定文件夹,该文件夹中的所有文件以及这些单个文件中的代码行将被计算在内,并在控制台上显示文件名和其中的代码行。这是我的代码段...
Map<String, Integer> result = new HashMap<String, Integer>();
File directory = new File(chooser.getSelectedFile().getAbsolutePath());
File[] files = directory.listFiles();
for (File file : files)
{
if (file.isFile())
{ Scanner scanner = new Scanner(new FileReader(file));
int lineCount = 0;
try
{ for (lineCount = 0; scanner.nextLine() != null; lineCount++) ;
} catch (NoSuchElementException e)
{ result.put(file.getName(), lineCount);
}
}
}
for (Map.Entry<String, Integer> entry : result.entrySet())
{ System.out.println(entry.getKey() + " ==> " + entry.getValue());
} }
但我想再添加一个功能,它还应该显示所有文件的总行数,假设这 6 个单独的文件有 10 行代码,每个文件有 10 行代码,然后行数总和为 10*6,即读取的总行数为 60 行,如何实现这一点请告知
为什么不为每个 Map 条目值添加一个计数器,并将其添加到计数器/累加器中,然后打印出来:
Map<String, Integer> result = new HashMap<String, Integer>();
File directory = new File(chooser.getSelectedFile().getAbsolutePath());
File[] files = directory.listFiles();
for (File file : files)
{
if (file.isFile())
{
Scanner scanner = new Scanner(new FileReader(file));
int lineCount = 0;
try
{ for (lineCount = 0; scanner.nextLine() != null; lineCount++);
} catch (NoSuchElementException e)
{ result.put(file.getName(), lineCount);
}
}
}
int lineCounter = 0;
for (Map.Entry<String, Integer> entry : result.entrySet())
{
System.out.println(entry.getKey() + " ==> " + entry.getValue());
lineCounter+=entry.getValue();
}
System.out.println(String.valueOf(lineCounter));
要显示您正在读取的所有文件的总行数,您需要将每个文件的行数汇总到另一个变量中。
Map<String, Integer> result = new HashMap<String, Integer>();
File directory = new File(chooser.getSelectedFile().getAbsolutePath());
File[] files = directory.listFiles();
int totalLineCount = 0;
for (File file : files)
{
if (file.isFile())
{ Scanner scanner = new Scanner(new FileReader(file));
int lineCount = 0;
try
{ for (lineCount = 0; scanner.nextLine() != null; lineCount++) ;
} catch (NoSuchElementException e)
{ result.put(file.getName(), lineCount);
totalLineCount += lineCount;
}
}
}
System.out.println("Total line count = "+ totalLineCount);
for (Map.Entry<String, Integer> entry : result.entrySet())
{ System.out.println(entry.getKey() + " ==> " + entry.getValue());
} }
因此,如果您有 10 个文件,每个文件有 6 行,则 totalLineCount 应为 60。