0
사용자가 선택한 폴더에서 Java 파일을 읽는 Java 코드를 개발했습니다. 각 파일에 몇 줄의 코드가 있는지 표시하고 .java 파일 만 읽으며 콘솔에 최종 결과가 표시되지만 파일이 전혀없는 폴더가 있다고 가정 해 보겠습니다. 이런 경우에 .java 파일이없는 폴더 나는 예외를 잡아서 폴더 안에 .java 파일이 없다는 메시지를 표시하여 사용자 정의 된 메시지를 표시하려고합니다. 어떻게 달성 할 것인지 조언 해주십시오. 코드의 ..Java에서 catch 예외에 관한 내용
public static void main(String[] args) throws FileNotFoundException {
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("C:" + File.separator));
chooser.setDialogTitle("FILES ALONG WITH LINE NUMBERS");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{ Map<String, Integer> result = new HashMap<String, Integer>();
File directory = new File(chooser.getSelectedFile().getAbsolutePath());
int totalLineCount = 0;
File[] files = directory.listFiles(new FilenameFilter(){
@Override
public boolean accept(File directory, String name) {
if(name.endsWith(".java"))
return true;
else
return false;
}
}
);
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("*****************************************");
System.out.println("FILE NAME FOLLOWED BY LOC");
System.out.println("*****************************************");
for (Map.Entry<String, Integer> entry : result.entrySet())
{ System.out.println(entry.getKey() + " ==> " + entry.getValue());
}
System.out.println("*****************************************");
System.out.println("SUM OF FILES SCANNED ==>"+"\t"+result.size());
System.out.println("SUM OF ALL THE LINES ==>"+"\t"+ totalLineCount);
}
}