zoukankan      html  css  js  c++  java
  • JAVA

    服务器:Tomcat 9

    注意问题:配置文件应该放入Tomcat的正式工程目录中测试。

    可用代码:

    package com.daoen.rtis.test;
    
    import java.io.FileReader;
    import java.io.IOException;
    import java.io.Reader;
    import java.util.Properties;
    
    public class Test {
    
    	public void GetPro() {
    
    		try {
    
    			String fileName = "db.txt";// property文件名
    			String filePath = getWebPath(fileName);// 得到property文件在web工程里的全路径名称
    
    			System.out.println(filePath);
    
    			Reader myReader = new FileReader(fileName);// 读取property文件
    
    			Properties prop = new Properties();// 创建Properties类
    			prop.load(myReader);// 用Properties类对象加载文件
    
    			System.out.println(prop.getProperty("ip"));
    			System.out.println(prop.getProperty("port"));
    			System.out.println(prop.getProperty("user"));
    			System.out.println(prop.getProperty("password"));
    
    			myReader.close();
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
    
    	// 得到web容器路径
    	// 注意:要在正式发布的web工程里面加入文件,不能在源代码工程里测试。
    	public static String getWebPath(String fileName) {
    		// file:/D:/JavaWeb/.metadata/.me_tcat/webapps/TestBeanUtils/WEB-INF/classes/
    		String path = Thread.currentThread().getContextClassLoader().getResource("").toString();
    
    		// 去掉返回路径中各种不需要的东西
    		path = path.replace('/', '\'); // 将/换成
    		path = path.replace("file:", ""); // 去掉file:
    		// path = path.replace("classes\", ""); // 去掉class
    		path = path.substring(1); // 去掉第一个\,如 D:JavaWeb...
    
    		// 如果有文件名,则在路径上加入文件名
    		if (fileName.isEmpty() == false) {
    			path += fileName;
    		}
    
    		return path;
    	}
    
    }  

    参考:

    https://blog.csdn.net/shokuninn/article/details/53808629

    https://www.cnblogs.com/lingtiaoti/p/9500322.html

  • 相关阅读:
    poj 3071 Football (概率dp)
    CF1408G Clusterization Counting
    2-sat
    线段树优化建图
    SP5971 LCMSUM
    [NOI2020]命运
    SP19149 INS14H
    Atcoder ARC-068
    CF908G New Year and Original Order
    (四)、Fiddler打断点
  • 原文地址:https://www.cnblogs.com/sunylat/p/10910854.html
Copyright © 2011-2022 走看看