`
步行者
  • 浏览: 167463 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

java中的Class.getResource()方法

    博客分类:
  • JAVA
阅读更多

当你想要在java类包中某个层次上添加一个非java文件,像资源文件,XML配置文件

或其他格式文件的时候, Class.getResource() 是一个很有用的方法,它不是根据

绝对路径来定位某个资源(文件),而是根据相对类路径来定位资源。当我们用绝对路径

来定位java类包中某个层次的资源时,项目的部署和迁移可能会出现问题,而且跨平台

运行也会出现问题。(像 "c:/1.txt"这个文件路径 在linux里是不能被识别的)

 

下面显示了一个类层次:

 

+bin--

    +test_1--

        Test.class

        +test_2--

            hello_en.txt

    hello_zh.txt

 

注意: 资源文件必须在编译后类路径里才能通过Class.getResource() 的方式被定位 ,

而不是在源文件路径里。

 

下面是Test_1的代码用来定位和读取hello_en.txt文件

package test_1;

import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.net.URISyntaxException;
import java.net.URL;
import java.io.FileReader;

public class Test {
	public static void main(String[] args) throws URISyntaxException, IOException {
		//根据类包根层次的相对路径来定位hello_en.txt文件 
		URL url = Test_1.class.getResource("/test_1/test_2/hello_en.txt");
		//定位hello_en.txt的另外一种方式  
		//根据当前类文件Test_1.class的相对路径来定位hello_en.txt文件  
		//URL url = Test_1.class.getResource("test_2/hello_en.txt"); 
		File file = new File(url.toURI());
	    StringBuffer buffer = new StringBuffer();
		Reader reader = new FileReader(file); 
		int ch = reader.read();
		while(ch != -1){
			buffer.append((char)ch);
			ch = reader.read();
		}
		reader.close();
		System.out.println(buffer.toString());
	}
}

 

运行这个类文件,输出结果如下(hello_en.txt 文件的内容为 hello !):


    hello !

 

 

定位hello_zh.txt文件的代码片段如下(当然也有两种方式):

 

URL url = Test_1.class.getResource("/hello_zh.txt");

 或者

URL url = Test_1.class.getResource("../hello_zh.txt");
 

 

还有一点需要注意 ,用

 

File file = new File(url.toURI());

来获取一个File对象,最好不能用

 

File file = new File(url.getFile());

因为URL.getFile()返回的文件路径字符串自动将空格转换为了ASC2编码,如果在你的绝对文件路径中含有空格,就会无法定位到这个文件,当时在这快也确实让我迷惑了一下。


Class.getResourceAsStream() 也可以用于定位和获取资源文件,和Class.getResource差不多,不过返回的是一个InputStream对象。

 

 

 

分享到:
评论

相关推荐

    通讯录管理系统文档 Java设计

    URL url = LoginFrame.class.getResource("/image/main.jpg"); // 获得图片的URL Image image=new ImageIcon(url).getImage(); // 创建图像对象 BackgroundPanel gbPanel=new BackgroundPanel(image); // 创建背景...

    S2SH整合报错

    配置了日志之后打印出下列信息: ERROR main org.springframework.web.context.... at java.lang.Class.getConstructor0(Class.java:2640) at java.lang.Class.getDeclaredConstructor(Class.java:1953) ……

    Java声音播放程序源代码

    URL file1 = getClass().getResource(choics[0]); //声音文件1 URL file2 = getClass().getResource(choics[1]); //声音文件2 AudioClip sound1 = java.applet.Applet.newAudioClip(file1); //声音剪辑对象1 ...

    大一课程设计,java开发的切水果小游戏.zip

    java课程设计大作业,java、算法练手项目,适合初学java、数据结构的同学拿来学习研究,基于java、GUI开发的小游戏,程序都经过测试,可以直接运行,资源含程序运行所需的源码、资源文件等全部数据,有需要的可放心...

    解决java打包之后无法加载静态资源的问题SWTResourceManager.java源码

    这是因为通过class.getResource()方法在IDEA中运行的路径和生成jar包获取的的路径是不同的。打成jar包后,获取图片的路径中有"xxx.jar!"这里面的内容是不能够被操作系统识别出来的,因此直接通过路径来获取文件是不...

    Java路径问题解决方案汇集

     1、 URLTest.class.getResource(/).getPath();  URLTest.class.getResource(/).getFile();  URLTest.class.getClassLoader().getResource().getPath();  Thread.currentThread()....

    java坦克小游戏

    用java编写的一个坦克小游戏 ... import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.util.*;... //Image = Toolkit.getDefaultToolkit().getImage(Panel.class.getResource('')); } }

    java的小程序

    import java.util.Scanner; import javax.swing.*; import java.awt.*; import java.awt.event.*; import javax.imageio.*; ...public class Jsq{ ... blaf9.setIcon(new ImageIcon(getClass().getResource(s009...

    Java飞机大战源码

    此份源码是学习Java面向对象时做的小项目,用到swing,数组,简单可行,作为入门是再合适不过了,里面有相应的注释,详细。

    java-loadresource.rar

    Java加载资源文件的两种方法getResource与getResourceAsStream

    java做的抽奖转盘

    button.setIcon(new ImageIcon(getClass().getResource( "bt.png"))); button.setOpaque(false); button.setContentAreaFilled(false); button.setBorder(null); button.setBounds(277, 202, 139, 209); ...

    经典java小程序源代码合集.zip

    Image white= tk.getImage(cl.getResource("res/white.png")); Image black= tk.getImage(cl.getResource("res/black.png")); Image title= tk.getImage(cl.getResource("res/title.png")); Image temp; ...

    JDBC学习,java应用

    URL tupin1 = login.class.getResource("login1.jpg");//图片地址 Icon icon1= new ImageIcon(tupin1);//实列Icon JLabel bq1 = new JLabel(icon1);//向标签中加入图片 hname.add(bq1);//将标签加到容器 /...

    java课程设计论文个人通讯录管理系统.doc

    目 录 一、开发背景………………………………………………………………... URL url = LoginFrame.class.getResource("/image/main.jpg"); // 获得图片的URL Image image=new ImageIcon(url).getImage(); // 创建图像对

    JAVA程序综合设计数据库设计说明.doc

    Icon ro=new ImageIcon(getClass().getResource("g1.gif")); JLabel lb0=new JLabel("",ro,JLabel.CENTER); JLabel lb1=new JLabel(); JTextField tf1=new JTextField(10); JLabel lb2=new JLabel("密码:",JLabel....

    数据库工具类DatabaseUtil.java

    Class<? extends Object> clazz = resource.getClass(); java.lang.reflect.Method method = clazz.getMethod("close", null); method.invoke(resource, null); } catch (Exception e) { // e.printStackTrace()...

    java自定义弹窗Demo

    Icon icon = new ImageIcon(ConfirmDialog.class.getClassLoader().getResource("info.png")); ScaleIcon scaleIcon = new ScaleIcon(icon); JLabel iconLabel = new JLabel(scaleIcon); iconLabel....

    基于java的仿qq聊天程序的设计与实现 +代码

    String picurl = TalkFrame.class.getResource("pic").getPath() + File.separator; try { ImageIcon icon = new ImageIcon(picurl + str); showText.setCaretPosition(doc.getLength()); showText.insert...

    解决ckfinder2.4.1 for java与ckeditor集成时快速上传重名不显示的jar包

    URL dirURL = ConnectorServlet.class.getResource("/lang/");这名代码出现null值。有两种解决方案: 一、修改代码,增加if(null!=dirURL){……} 二、将官网下载来的CKFinder-2.4.1.jar包中的lang文件夹解压出来,放...

    java pdf 查看器

    url = getClass().getResource(name); icon = new ImageIcon(url); if (icon == null) { System.out.println("Couldn't find " + url); } } catch (Exception e) { System.out.println("Couldn't find " + ...

Global site tag (gtag.js) - Google Analytics