java访问资源文件

Java code

import java.io.FileInputStream;   
import java.io.FileOutputStream;   
import java.util.Properties;   
  
public class PropertyEditor {   
    public static void main(String[] args) throws Exception {   
        Properties prop = new Properties();// 属性集合对象   
        FileInputStream fis = new FileInputStream("prop.properties");// 属性文件输入流   (相对于根目录下的文件名,要加上包名 “src/prop.properties”)
        prop.load(fis);// 将属性文件流装载到Properties对象中   
        fis.close();// 关闭流   
  
        // 获取属性值,sitename已在文件中定义   
        System.out.println("获取属性值:sitename=" + prop.getProperty("sitename"));   
        // 获取属性值,country未在文件中定义,将在此程序中返回一个默认值,但并不修改属性文件   
        System.out.println("获取属性值:country=" + prop.getProperty("country", "中国"));   
  
        // 修改sitename的属性值   
        prop.setProperty("sitename", "中国");   
        // 添加一个新的属性studio   
        prop.setProperty("studio", "Boxcode Studio");   
        // 文件输出流   
        FileOutputStream fos = new FileOutputStream("prop.properties");   
        // 将Properties集合保存到流中   
        prop.store(fos, "Copyright (c) Boxcode Studio");   
        fos.close();// 关闭流   
    }   
}  
资源文件

sitename=\u4E2D\u56FD
siteurl=www.abcjava.com   
studio=Boxcode Studio


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java Swing中,源文件通常用于存储应用程序的外观和文本信息,以便可以轻松地进行本地化和主题化。源文件可以包含图像、颜色、字体、字符串等各种类型的数据。 Java Swing中的源文件通常使用.properties文件格式。这种格式是一种简单的键值对格式,其中每个键值对表示一个源项。以下是一个示例的源文件内容: ``` # 注释行以#开头 button.label=Click Me! button.background=#FF0000 button.font=Arial, 12, bold ``` 在上面的示例中,`button.label`表示一个按钮的标签文本,`button.background`表示按钮的背景颜色,`button.font`表示按钮的字体。 要在Java Swing中使用源文件,可以使用`ResourceBundle`类来加载和访问源。`ResourceBundle`类提供了一组方法来根据指定的源文件名称和Locale加载源文件,并通过键来获取对应的值。 以下是一个使用源文件的示例代码: ```java import java.util.ResourceBundle; public class Main { public static void main(String[] args) { // 加载源文件 ResourceBundle bundle = ResourceBundle.getBundle("resources", Locale.getDefault()); // 获取源值 String buttonLabel = bundle.getString("button.label"); String buttonBackground = bundle.getString("button.background"); String buttonFont = bundle.getString("button.font"); // 使用源值创建按钮 JButton button = new JButton(buttonLabel); button.setBackground(Color.decode(buttonBackground)); button.setFont(Font.decode(buttonFont)); // 其他操作... } } ``` 在上面的示例中,`ResourceBundle.getBundle("resources", Locale.getDefault())`用于加载名为"resources"的源文件。然后,通过`bundle.getString(key)`方法可以获取源文件中对应键的值。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值