我正在努力学习java。 这就是我正在尝试做的事情。我在 intelij 中创建了一个项目,并在其中尝试从文件中获取 usrrename 和密码并在类中使用它。 经过一段时间的搜索后,我发现 util.property 可以满足需要。所以我创建了一个类来获取该属性。
public class Login {
public String[] getLoginValues() throws IOException{
String token = "";
Properties prop=new Properties();
String LoginFileName="login.properties";
InputStream inputStream =getClass().getClassLoader().getResourceAsStream(LoginFileName);
if(inputStream!= null){
prop.load(inputStream);
}
else{
throw new FileNotFoundException("Property File"+LoginFileName+"not found in the classpath");
}
Date time= new Date(System.currentTimeMillis());
System.out.println("Created at"+time);
//get property values & print it out
String userName=prop.getProperty("user.name");
String password=prop.getProperty("password");
String apiUrl=prop.getProperty("api.url");
}
现在我想要这些值 -
username,password, & apiurl
待退回。但众所周知,它不能返回多个值
我想使用登录类中的值在我使用它们的主类中使用。 这是主类的代码 -
public class AutomationCount {
// login lg=new login();
protected static String token = "";
protected static String userName = ;//username
protected static String password = ;//password
protected static String apiUrl = ;//apiUrl
那么我需要在那里做什么。你能帮我一下吗?
最佳答案
有很多选项可以解决这个问题。有些是比其他更好的主意,但这取决于您的情况。其中一些选项包括:
1) 返回一个字符串数组,其中数组中的每个位置都是一个特定属性
String results = new String[3];
results[0] = userName;
results[1] = password;
results[2] = apiUrl;
return results;
2) 返回 Credentials 类的实例,例如:
public class Credentials {
public String userName;
public String password;
public String apiUrl;
}
3) 返回已有的 Properties 对象
4)返回属性的映射
Map<String, String> credentials = new HashMap<String, String>();
credentials.put("userName", userName);
credentials.put("password", password);
credentials.put("apiUrl", apiUrl);
return credentials;
或者,您的 Login 类可以读取其构造函数中的值,并提供 getter 方法来单独检索它们,如下所示:
public class Login {
private String userName;
private String password;
private String apiUrl;
public Login() throws IOException{
String token = "";
Properties prop=new Properties();
String LoginFileName="login.properties";
InputStream inputStream =getClass().getClassLoader().getResourceAsStream(LoginFileName);
if(inputStream!= null){
prop.load(inputStream);
} else {
throw new FileNotFoundException("Property File"+LoginFileName+"not found in the classpath");
}
Date time= new Date(System.currentTimeMillis());
System.out.println("Created at"+time);
//get property values & print it out
userName=prop.getProperty("user.name");
password=prop.getProperty("password");
apiUrl=prop.getProperty("api.url");
}
public String getUserName() {
return userName;
}
public String getPassword() {
return password;
}
public String getApiUrl() {
return apiUrl;
}
}
关于java - 在java中如何使用属性将多个值从一个类传递到另一个类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28979045/