import java.io.File;
import javax.swing.JList;
public class FileUtils {
private static final File dir = null;
private static Object String;
/**
* @param args
* @throws IllegalAccessException
*/
public static String[] listDirectory(File dir) throws IllegalAccessException{
//判断File对象dir是否存在,使用File类的exists()方法
if(!dir.exists()){
//如果不存在,抛出异常
throw new IllegalAccessException("目录" + dir +"不存在。");
}
//判断dir是否是目录,使用File类的isDirectory()方法
if(!dir.isDirectory()){
throw new IllegalArgumentException(dir + "不是目录");
}
//获得指定目录dir下的文件及子目录并输出(1.list();2.listFiles())
//使用list()方法实现
String[] fileNames = dir.list();
for(String s : fileNames)
System.out.println(s);
//使用listFiles()方法实现只列出目录下的所有文件名称
File[] files = dir.listFiles();
return fileNames;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
FileUtils.listDirectory(new File("D:"));
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
import javax.swing.;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.;
import java.io.File;
public class FileUtilsFrame {
private static JLabel infoLabel;
private static JSlider slider;
private static JList list;
private static ListModel fileName;
private static JList fileList;
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
final JFrame frm = new JFrame("");
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JList<String> jList = new JList<>(FileUtils.listDirectory(new File("D:")));
frm.add(jList);
JMenuBar mbar = new JMenuBar();
frm.setJMenuBar(mbar);
JMenu m1 = new JMenu("files");
JMenu m2 = new JMenu("list");
mbar.add(m1);
mbar.add(m2);
frm.setBounds(400, 200, 200, 300);
frm.setVisible(true);
}
}