« | August 2025 | » | 日 | 一 | 二 | 三 | 四 | 五 | 六 | | | | | | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | | | | | | | |
| 公告 |
戒除浮躁,读好书,交益友 |
Blog信息 |
blog名称:邢红瑞的blog 日志总数:523 评论数量:1142 留言数量:0 访问次数:9692160 建立时间:2004年12月20日 |

| |
[java语言]未公开的mustang核心秘密(五): java判断文件类型和文件打开  原创空间, 软件技术, 电脑与网络
邢红瑞 发表于 2007/7/22 11:01:44 |
最早以前,写一个文件下载的程序,判断文件的类型是个大问题,不断的根据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()); } }
} }} |
|
|