Sprint读取配置文件内容格式的String

package unit.test;

import java.io.IOException;
import java.util.Properties;

import org.junit.Test;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

public class StringPropertyLoadTest {

	@Test
	public void testLoad(){
		
		String protertryStr = 
			"spring.redis.database=0\n"+
			"spring.redis.host=localhost\n"+
			"spring.redis.port=8080\n"+
			"spring.redis.password=\n"+
			"#this is comment! \n"+
			"spring.redis.timeout=0\n"+
			"spring.redis.pool.max-active=8 #abcd   \n"+
			"spring.redis.pool.max-wait=-1\n"+
			"spring.redis.pool.max-idle=8\n"+
			"spring.redis.pool.min-idle=0\n";

		
		ByteArrayResource resource = new ByteArrayResource(protertryStr.getBytes(), protertryStr);
		try {
			Properties properties  =PropertiesLoaderUtils.loadProperties(resource);
			
			properties.entrySet().forEach(p ->{
				System.out.println(p.getKey()+"="+p.getValue());
			});
			
		} catch (IOException e) {
			
			e.printStackTrace();
		}
		
		
	}
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用Spring Boot的MVC框架读取URL的内容并写入响应可以通过以下步骤实现: 1. 创建一个Controller类,并使用@Controller注解进行标记。 2. 在Controller类中创建一个处理GET请求的方法,并使用@GetMapping注解进行标记。 3. 在该方法中,使用@RequestParam注解获取URL中的参数值。 4. 使用Java的URL类创建URL对象,将参数值追加到URL中。 5. 使用Java的URLConnection类打开URL连接,并获取连接的输入流。 6. 使用Java的BufferedReader对输入流进行读取,并将读取内容存储到一个字符串变量中。 7. 关闭输入流和连接。 8. 将读取内容写入响应,可以使用@ResponseBody注解将字符串作为响应的内容返回。 以下是一个示例代码: ```java import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; @Controller public class MyController { @GetMapping("/get-content") @ResponseBody public String getContentFromURL(@RequestParam String url) throws IOException { URL websiteURL = new URL(url); URLConnection connection = websiteURL.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder content = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { content.append(line); } reader.close(); connection.disconnect(); return content.toString(); } } ``` 在上述示例中,我们创建了一个`getContentFromURL`方法,该方法接收一个`url`参数,读取该URL的内容,并将内容字符串形式返回作为响应。通过访问`/get-content?url={url}`的URL,可以将URL的内容返回给客户端。注意需要处理可能的异常情况,并在实际应用中对URL的合法性进行验证和参数的过滤。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值