处理properties文件,copy文件

本文介绍了一个Java程序,该程序实现文件及目录的复制功能,并演示如何从properties文件中加载配置信息。此外,还提供了处理文件输入输出流的具体方法。

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

<!--StartFragment -->
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


public class ContextLoad {

public static void main(String args[]) {

//上下文加载
// ClassPathXmlApplicationContext appContext = null;
//     appContext = new ClassPathXmlApplicationContext(
//             new String[] {"system-architecture-research.xml"});
//     
//     BeanFactory factory = (BeanFactory) appContext;
//     System.out.println(factory.getBean("dataSource"));
//     System.out.println(factory.getBean("dataSource").getClass());

//得到系统换行符
// String rn = System.getProperty("line.separator");
// System.out.println("here is "+rn+" test!");

//properties文件路径src/test/test.properties
// InputStream in = Thread.currentThread().getClass().getResourceAsStream("/test/test.properties");
// Properties p = new Properties();
// try {
// if(in==null){
// System.out.println("load file error !");
// }else{
// p.load(in);
// System.out.println(p);
// System.out.println("############################");
// //文件所有的key值
// Enumeration enu = p.propertyNames();     //取出所有的key
// while( enu .hasMoreElements()){
// String temp = (String) enu.nextElement();
//     System.out.println("key="+ temp);
//     System.out.println("value="+p.getProperty(temp));
// }
// System.out.println("############################");
// }
//
// } catch (IOException e) {
// e.printStackTrace();
// }
File source = new File("D:/aaa/");
File target = new File("D:b/ccc/");

copyFile(source,target);
}

/**
 * 拷贝文件到目的地址,这里目的地址是一个目录
 * @param source
 * @param target
 * 源路径的文件(可能是不同文件层次结构的)都拷贝到了目标地址的同一个目录下
 */
public static void copyFile(File source,File target){

File targetCopy = new File(target,source.getName());
if(source.exists()){//文件或目录存在

System.out.println("copy的文件或者目录存在!!!");
if(!target.exists()){
//mkdir无法创建多级目录
target.mkdirs();//创建多级目录
}

if(source.isFile()){

InputStream in = null;
OutputStream out = null;
try {
//这里的对象必须是一个文件字符串,如果是目录,则相当于找不到file
in = new FileInputStream(source);
out = new FileOutputStream(targetCopy);
@SuppressWarnings("unused")
int readReturn;
int cacheLen = 1024;
byte cache[] = new byte[cacheLen];
//每次读取1024字节的内容到内存中,也就是1M
while((readReturn = in.read(cache)) != -1){
out.write(cache, 0,cacheLen);
out.flush();
}

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{

//对于处理流,中间可能存在一些匿名的流
//最终关闭处理流即可,被包装的流会相应的关闭
try {
if(in !=null){
//在try语句初始化in时可能存在异常
//那么in就==null,所以要进行if判断
in.close();
}
if(out !=null){
out.close();//close方法里封装了flush方法
}
} catch (IOException e) {
e.printStackTrace();
}
}

}else if(source.isDirectory()){
//如果是目录,则递归拷贝
File dirs[] = source.listFiles();
for(int i=0;i<dirs.length;i++){
copyFile(dirs[i],target);
}
}

}else{
System.out.println("copy的文件或者目录不存在!!!");
}
}

}
### 如何将 Properties 文件转换为 YML 格式的最佳实践 #### 使用手动方法进行转换 对于简单的 `properties` 文件,可以按照以下原则将其转换成 `YAML` 文件: - **键值对映射** 如果 `properties` 中存在如下形式的键值对: ```properties app.name=MyApp server.port=8080 ``` 可以直接对应到 YAML 的格式下: ```yaml app: name: MyApp server: port: 8080 ``` - **处理多层嵌套结构** 对于带有层次感的配置项,在 `properties` 文件里通常通过`.`来分隔不同级别的节点;而在 YAML 中,则可以通过缩进来表示这种关系。 假设有一个这样的 properties 设置: ```properties spring.datasource.url=jdbc:mysql://localhost:3306/testdb?useSSL=false&serverTimezone=UTC spring.datasource.username=root spring.datasource.password=admin123 ``` 转换成 YAML 后会变成这样: ```yaml spring: datasource: url: jdbc:mysql://localhost:3306/testdb?useSSL=false&serverTimezone=UTC username: root password: admin123 ``` #### 利用编程语言实现自动化转换 为了提高效率并减少人为错误的发生率,还可以编写脚本来完成这项工作。这里给出 Python 实现的一个简单例子: ```python import os def convert_properties_to_yaml(input_file_path, output_file_path): with open(input_file_path, 'r') as f_in,\ open(output_file_path, 'w') as f_out: current_indent_level = 0 last_key_parts = [] for line in f_in.readlines(): stripped_line = line.strip() if not stripped_line or stripped_line.startswith('#'): continue key_value_pair = stripped_line.split('=', maxsplit=1) if len(key_value_pair) != 2: raise ValueError(f'Invalid property format at line "{line}"') key, value = map(str.strip, key_value_pair) new_key_parts = key.split('.') common_prefix_length = min(len(last_key_parts), len(new_key_parts)) while common_prefix_length > 0 and \ last_key_parts[:common_prefix_length] == new_key_parts[:common_prefix_length]: common_prefix_length -= 1 indent_spaces = " "*len(new_key_parts[:-1]) f_out.write(f'{indent_spaces}{new_key_parts[-1]}: {value}\n') last_key_parts = new_key_parts.copy() if __name__ == '__main__': input_fp = './example.properties' output_fp = './output.yaml' try: convert_properties_to_yaml(input_fp, output_fp) print("Conversion successful!") except Exception as e: print(e) ``` 此代码片段展示了如何读取 `.properties` 文件并将它们逐行解析为相应的 YAML 结构[^4]。 #### 工具辅助转换 除了上述两种方式外,也可以借助第三方库或在线服务来进行转换操作。然而需要注意的是,并不是所有的在线工具都能完美无误地执行这一过程,因此建议先测试少量样本再决定是否大规模应用这些工具[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值