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

最早以前,写一个文件下载的程序,判断文件的类型是个大问题,不断的根据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());
    }
   }

  }
 }
}

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值