import java.io.File;
import java.io.IOException;
public class FileUtils {
private static String[] filenames;
public static String fileDir(File file) throws IOException {
if (!file.exists()) {
System.out.println("目录不存在");
throw new IOException();
}
if (!file.isDirectory()) {
System.out.println(file + "不是目录");
throw new IOException();
}
filenames = file.list();
String mes = "";
for (String str : filenames) {
mes += str + '\n';
}
return mes;
}
public static String eachFileDir(String str) throws IOException {
String mes = "";
for (int i = 0; i < filenames.length; i++) {
// 获取文件后缀名
String postfix = filenames[i].substring(filenames[i].lastIndexOf("."));
if (postfix.equalsIgnoreCase(str)) {
mes += filenames[i] + '\n';
}
}
return mes;
}
}
此为实现调用文件功能的代码;
import java.awt.*; import java.io.File; import java.io.IOException; import javax.swing.*; public class ImageViewer { private JTextArea list_area; private JPanel panel; private JFrame frame; public ImageViewer() { makeFrame(); } private void makeFrame() { frame = new JFrame("ImageViewer"); makeMenuBar(); // Container contentPane = frame.getContentPane(); // contentPane.setLayout(new BorderLayout(6, 6)); // JLabel fileLabel = new JLabel("当前还没有打开图片文件"); // JLabel statusLabel = new JLabel("ImageViewer1.0"); // // // // JPanel panelW = new JPanel(new FlowLayout(FlowLayout.LEFT)); // JPanel panelInW = new JPanel(new GridLayout(2,1,2,2)); list_area= new JTextArea(); list_area.setEnabled(false);/* list_area设置不可编辑 */ try { // 调用fileDir获取文件里面的所有文件内容 list_area.setText(FileUtils.fileDir(new File("audio"))); } catch (IOException e) { e.printStackTrace(); } list_area.setBackground(Color.BLACK); panel=new JPanel(new BorderLayout()); panel.add(list_area,BorderLayout.CENTER); frame.add(panel); frame.setSize(260, 350); frame.setVisible(true); } private void makeMenuBar() { JMenuBar menubar = new JMenuBar(); frame.setJMenuBar(menubar); JMenu fileMenu = new JMenu("File"); menubar.add(fileMenu); JMenuItem openItem = new JMenuItem("OPEN"); fileMenu.add(openItem); JMenuItem quitItem = new JMenuItem("QUIT"); fileMenu.add(quitItem); JMenu helpMenu = new JMenu("help"); menubar.add(helpMenu); JMenuItem aboutItem = new JMenuItem("About ImageViewer"); helpMenu.add(aboutItem); } public static void main(String[] args) { // TODO Auto-generated method stub new ImageViewer(); } }
此为GUI界面的代码并实现功能连接。其效果如下