未公开的mustang核心秘密(五): java判断文件类型和文件打开

来源:互联网 发布:软件界面设计欣赏 编辑:程序博客网 时间:2024/04/30 06:16

最早以前,写一个文件下载的程序,判断文件的类型是个大问题,不断的根据MimetypesFile添加,现在mustang做了相应的类FileTypeMap。
下面是个例子,
package test;

import javax.activation.*;
import java.io.*;

public class FileTypes {
 public static void main(String args[]) {
  FileTypeMap map = FileTypeMap.getDefaultFileTypeMap();
  String path;
  if (args.length == 0) {
   path = "d:/";
  } else {
   path = args[0];
  }
  File dir = new File(path);
  File files[] = dir.listFiles();
  for (int i = 0; i < files.length; i++) {
   File file = files[i];
   System.out
     .println(file.getName() + ": " + map.getContentType(file));
  }
 }
}
可以显示出文件的类型,下载还是打开,遗憾的是java 5提供的for each mustang却不支持了,for (File file: files) 将是个错误。
java实现用本地程序打开文件,就是实现ShellExecute的功能是个困难的事情,在mustang这个变得simple。

import java.awt.*;
import java.io.*;

public class DesktopTest {
 public static void main(String args[]) {
  if (!Desktop.isDesktopSupported()) {
   System.err.println("Desktop not supported!");
   System.exit(-1);
  }
  Desktop desktop = Desktop.getDesktop();
  String path;
  if (args.length == 0) {
   path = "d:/";
  } else {
   path = args[0];
  }
  File dir = new File(path);
  File files[] = dir.listFiles();
  for (int i = 0; i < files.length; i++) {
   File file = files[i];
   if (desktop.isSupported(Desktop.Action.OPEN)) {
    System.out.println("Opening... " + file.getName());
    try {
     desktop.open(file);
    } catch (IOException ioe) {
     System.err.println("Unable to open: " + file.getName());
    }
   }

  }
 }
}

 
原创粉丝点击