java Properties存取操作例子(无注解)

本文介绍了一个使用Java实现的新闻内容保存与读取的方法。该方法通过Properties类来存储和加载新闻内容到指定路径的文件中。首先将新闻内容保存为属性文件,然后从同一路径读取内容进行验证。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


public void saveToFile(String newsContent)
{
Properties prop = new Properties();
try
{
InputStream is = NewsPush.class.getClassLoader().getResourceAsStream("newspath.properties");
prop.load(is);
String newsPath = prop.getProperty("path");
is.close();
OutputStream os = new FileOutputStream(newsPath);
prop.clear();
prop.setProperty("content", newsContent);
prop.store(os, "push news content");
os.close();
}
catch(IOException e)
{
log.debug("saveToFile error:"+e);
e.printStackTrace();
}
}

public String getSavedContent()
{
String content = null;
Properties prop = new Properties();
InputStream is = NewsPush.class.getResourceAsStream("/newspath.properties");
try
{
prop.load(is);
String newsPath = prop.getProperty("path");
is.close();
is = new FileInputStream(newsPath);
prop.load(is);
content = prop.getProperty("content");
is.close();
}
catch(IOException e)
{
log.debug("Get saved content error:"+e);
e.printStackTrace();
}
return content;
}
### Spring Boot 中使用注解配置 Redis 在 Spring Boot 应用程序中集成 Redis 并通过注解方式进行操作是一项常见的需求。为了实现这一目标,应用程序需引入必要的依赖并进行适当配置。 #### 添加 Maven 依赖 首先,在 `pom.xml` 文件中加入如下依赖来支持 Redis 连接: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 此依赖会自动导入所有必需组件以简化开发过程[^1]。 #### 配置文件设置 接着修改项目的 application.properties 或者 application.yml 来指定连接到 Redis 实例所需的参数: 对于 properties 格式的配置文件: ```properties spring.redis.host=localhost spring.redis.port=6379 ``` 而对于 YAML 格式则可以这样写: ```yaml spring: redis: host: localhost port: 6379 ``` 这些属性定义了主机地址以及端口号,默认情况下本地运行的 Redis 将监听于上述设定值上[^2]。 #### 注解驱动编程模型 为了让开发者能够更方便快捷地利用 Redis 的功能特性,Spring Data 提供了一系列便捷的方法和接口用于数据存取操作。其中最常用的就是 @Cacheable 和其他缓存相关联的注释标签。 下面是一个简单的例子展示怎样把对象存储至 Redis 缓存里,并且当请求相同键名的数据时可以直接返回已存在的记录而不是重新计算或查询数据库获取新结果。 创建服务类 ServiceImpl.java 如下所示: ```java import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; @Service public class UserService { private final UserRepository userRepository; public UserService(UserRepository userRepository){ this.userRepository = userRepository; } @Cacheable(value="users", key="#id") public User getUserById(Long id) { System.out.println("Fetching from database..."); return userRepository.findById(id).orElseThrow(() -> new RuntimeException("User not found")); } } ``` 在这个案例里面,每当调用 `getUserById()` 方法的时候都会先检查名为 "users" 的缓存区域是否存在对应的 entry;如果存在就直接取出该条目作为方法的结果返回给调用方而不会执行实际业务逻辑中的查找动作[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值