- package main;
- /**
- * 资源加载工具类
- * 【方法接口】
- * public static ImageIcon getImageIcon(String imagePath)
- * 返回imagePath路径下图像文件创建的ImageIcon对象
- * public static Clip getClip(String soundPath)
- * 返回soundPath路径下音频文件创建的Clip对象
- * */
- import java.io.*;
- import javax.swing.*;
- import javax.sound.sampled.*;
- public class ResourceLoading
- {
- private static ResourceLoading instance=new ResourceLoading();
-
- /**
- * 私有化构造函数,不让创建对象
- * */
- private ResourceLoading(){}
-
- /**
- *
- * 返回
- *
- * */
- public static ImageIcon getImageIcon(String imagePath)
- {
-
- InputStream imageIn=instance.getClass().getClassLoader().getResourceAsStream(imagePath);
- byte[] imageDate=new byte[1024*1024];
- try
- {
- imageIn.read(imageDate);
- }catch(IOException e)
- {
- e.printStackTrace();
- throw new RuntimeException("图像"+imagePath+"载入错误!!!");
- }finally{
- try
- {imageIn.close();}catch(IOException e){}
- }
- return new ImageIcon (imageDate);
- }
-
-
-
- public static Clip getClip(String soundPath)
- {
- Clip clip=null;
- try
- {
- InputStream soundIn=instance.getClass().getClassLoader().getResourceAsStream(soundPath);
- //System.out.println("found sound at"+soundIn);
- Line.Info linfo=new Line.Info(Clip.class);
- Line line =AudioSystem.getLine(linfo);
- clip=(Clip)line;
- AudioInputStream ais=AudioSystem.getAudioInputStream(soundIn);
- clip.open(ais);
- soundIn.close();
- ais.close();
- }catch (Exception e){
- e.printStackTrace();
- }
- return clip;
- }
-
- }
复制代码 以上是从类加载路径下加载资源的代码,有没有更好更优化的方法,可以使打包成jar包的时候也能加载资源? |