我試圖從文件夾中讀取多個文本文件,但我得到一個奇怪的結果閱讀從不同的目錄中的多個文本文件,也許你能幫助我理解it.So使用掃描儀
File folder;
int result;
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("."));
chooser.setDialogTitle("choosertitle");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
//
// disable the "All files" option.
//
chooser.setAcceptAllFileFilterUsed(false);
//
if (chooser.showOpenDialog(chooser) == JFileChooser.APPROVE_OPTION) {
System.out.println("getSelectedFile() : "
+ chooser.getSelectedFile());
folder = chooser.getSelectedFile();
Scanner in = null;
for (File fileEntry : folder.listFiles()) {
try {
in = new Scanner(new File(fileEntry.getName()));
} catch (FileNotFoundException e1) {
}
String CompositionName = in.next();
String Composer = in.next();
in.next();
String Duration = in.next();
parent.model.addRow(new Object[] { "", Composer,
CompositionName, TrackNumber, Duration });
in = null;
}
}
使用此方法,我得到只讀取文件夾的第一個文件。我得到一個NullPointerException String上的CompositionName = in.next();在第二個循環中,即使文件名是正確的。這種方式很有效,但我聽說這不是一個好習慣。
File folder;
int result;
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("."));
chooser.setDialogTitle("choosertitle");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
//
// disable the "All files" option.
//
chooser.setAcceptAllFileFilterUsed(false);
//
if (chooser.showOpenDialog(chooser) == JFileChooser.APPROVE_OPTION) {
System.out.println("getSelectedFile() : "
+ chooser.getSelectedFile());
folder = chooser.getSelectedFile();
Scanner in = null;
for (File fileEntry : folder.listFiles()) {
try {
System.out.println(fileEntry.getName());
in=null;
in = new Scanner(new File(folder.getAbsolutePath()+"\\"+fileEntry.getName()));
} catch (FileNotFoundException e1) {
}
String CompositionName = in.next();
String Composer = in.next();
in.next();
String Duration = in.next();
parent.model.addRow(new Object[] { "", Composer,
CompositionName, TrackNumber, Duration });
}
}
謝謝。
Works.Thank you very much.Have a day/night。 – Konstantinos