读一个或多个文件得到的文件名处理

来源:互联网 发布:基站数据转换成经纬度 编辑:程序博客网 时间:2024/05/16 10:00

 

   读一个文件还是读两个以上的文件得到的文件名

路径分隔符最好用File.separatorChar

1、用同一数组处理:

    前提:FileDialog dialog = new FileDialog(shell, SWT.MULTI);

              

                  FileDialogdialog = new FileDialog(shell, SWT.MULTI);                  String OpenFileName=dialog.open();   //最后一个文件名                   String[] fileNames=null;                    fileNames = dialog.getFileNames();  \\文件名,不包含路径 String path=dialog.getFilterPath();   \\路径if(fileNames.length==1){    fileNames[0]=path+\\+fileNames[0];//一个文件path为C:}else{    //方法1    for(int i=0;i<fileNames.length;i++)    {      fileNames[i]=path+fileNames[i]; //多个文件path为C:\     }     //方法2     Collection files = new ArrayList();                      if (dlg.open() != null) {                     String[] names = dlg.getFileNames();                     for (int i = 0, n = names.length; i < n; i++) {                     StringBuffer buf = new StringBuffer(dlg.getFilterPath()); \\不初始化buf.charAt为nullpointerException                      if (buf.charAt(buf.length() - 1) != File.separatorChar) //windows中File.separatorChar="\";                     buf.append(File.separatorChar);                     buf.append(File.separatorChar);//读取文件内容是需要C:\\                     buf.append(names[i]);                      files.add(buf.toString());      }    }}


方法2参考:  http://www.java2s.com/CN/Tutorial/Java/0280__SWT/GettingtheSelectedFileorFiles.htm
 

2、单独处理

一个文件

 Display display = new Display();    final Shell shell = new Shell(display);    FileDialog sdlg = new FileDialog(shell, SWT.OPEN);       String resultFileName=sdlg.open(); //C:\test.txt    String pathName=sdlg.getFilterPath();//C:      String fileName=sdlg.getFileName();//test.txt    display.dispose();


多个文件

Display display = new Display();    final Shell shell = new Shell(display);    FileDialog sdlg = new FileDialog(shell, SWT.MULTI);       String resultFileName=sdlg.open(); //最后一个文件名C:\last.txt    String pathName=sdlg.getFilterPath();//C:\    String[] fileName=sdlg.getFileNames();// first.txt   last.txt    display.dispose();