读取xml和Properties方法,Java常用读取配置文件方法

第一,如何读取Properties文件配置。

将配置文件放置在根目录下,,贴出配置文件

sourceFolder=E:\\BaiduNetdiskDownload
pack=\u5609\u5174\u4EA4\u6362,\u5609\u5584,\u79C0\u6D32,\u5609\u5174,\u5176\u4ED6
packpath=E:\\FileSortTest\\\u5609\u5174\u4EA4\u6362\\,E:\\FileSortTest\\\u5609\u5584\\,E:\\FileSortTest\\\u79C0\u6D32\\,E:\\FileSortTest\\\u5609\u5174\\,E:\\FileSortTest\\\u5176\u4ED6\\

贴出文件目录结构:

读取xml和Properties方法,Java常用读取配置文件方法_第1张图片

贴出读取代码:

public static void initProp(){
			ResourceBundle resource = ResourceBundle.getBundle("config");
			System.out.println(""+resource.getString("sourceFolder"));
			System.out.println(""+resource.getString("pack"));
			System.out.println(""+resource.getString("packpath"));
			sourceFolder = resource.getString("sourceFolder");
			pack = resource.getString("pack").split(",");
			packpath = resource.getString("packpath").split(",");
			logger.info("数据源--配置初始化完毕:"+sourceFolder);
			logger.info("文件分类关键词--配置初始化完毕:"+pack);
			logger.info("文件分类路径--配置初始化完毕:"+packpath);
		}

 

第二:读取xml文件:

本人之前用jsoup做过爬虫,所以读取xml文件用的是jsoup包,大家可以来学习呀

贴出jar包  jsoup-1.8.1.jar   直接从maven仓库下载就可以了。

话不多说直接贴代码,注释较多,就不细细讲解了。

public static void readXml(){
		String path = System.getProperty("user.dir").substring(0, System.getProperty("user.dir").length()-12)+"config.xml";
		logger.info("配置文件路径:"+path);
	    try {
			Document document = Jsoup.parse(new File(path), "utf-8");	
			String sourceFolder = "";
			if(document.getElementsByTag("sourceFolder").size()>0){
			sourceFolder = document.getElementsByTag("sourceFolder").get(0).text();
			}
			String destFolder = "";
			if(document.getElementsByTag("destFolder").size()>0){
				destFolder = document.getElementsByTag("destFolder").get(0).text();
			}
			if(document.getElementsByTag("packFolder").size()>0){
				String[] pack =  new String[document.getElementsByTag("packFolder").size()];
				String[] packpath =  new String[document.getElementsByTag("packFolder").size()];
				for (int i = 0; i < document.getElementsByTag("packFolder").size(); i++) {
					pack[i] = document.getElementsByTag("packFolder").get(i).getElementsByTag("pack").get(0).text();
					packpath[i] = document.getElementsByTag("packFolder").get(i).getElementsByTag("packpath").get(0).text();
				}
				System.out.println("pack"+pack);
				System.out.println("packpath"+packpath);
				System.out.println("sourceFolder"+sourceFolder);
				InitProperties.pack=pack;
				InitProperties.packpath= packpath;
				InitProperties.sourceFolder=sourceFolder;
				InitProperties.destFolder=destFolder;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

两个简单的小方法,希望对大家有所帮助。

你可能感兴趣的:(分享,学习)