package
oo;
import
java.io.FileReader;
import
java.io.FileWriter;
import
java.io.IOException;
import
java.util.Properties;
public
class
user {
public
static
void
main(String[]
args
) {
Properties
a
=
new
Properties();
try
{
a
.load(
new
FileReader(
"user.txt"
));
}
catch
(Exception
e
) {
//
TODO
: handle exception
System.
out
.println(
"文件不存在"
);
}
a
.setProperty(
"age"
,
"435"
);
a
.setProperty(
"id"
,
"2"
);
//如果键不存在,则新加键值对,如果键存在,则修改值
a
.setProperty(
"pwd"
,
"898"
);
try
{
//保存资源文件对象中所有的键值,第一个参数为写入流,第二个参数为注释
a
.store(
new
FileWriter(
"user.txt"
),
null
);
}
catch
(IOException
e
) {
//
TODO
Auto-generated catch block
e
.printStackTrace();
}
}
}
登录
package
oo;
import
java.io.FileReader;
import
java.util.Properties;
import
javax.swing.JOptionPane;
public
class
login {
public
static
void
main(String[]
args
) {
Properties
a
=
new
Properties();
String
q
=JOptionPane.
showInputDialog
(
null
,
"请输入你的账号"
);
int
w
=Integer.
parseInt
(JOptionPane.
showInputDialog
(
null
,
"请输入你的密码"
));
try
{
a
.load(
new
FileReader(
"Login.txt"
));
}
catch
(Exception
e
) {
//
TODO
: handle exception
JOptionPane.
showMessageDialog
(
null
,
"文件不存在"
);
}
String
aName
=
a
.getProperty(
"userName"
);
String
aPwd
=
a
.getProperty(
"pwd"
);
if
(
q
.equals(
aName
)&&
q
.equals(
aPwd
)){
JOptionPane.
showMessageDialog
(
null
,
"登录成功"
);
}
else
{
JOptionPane.
showMessageDialog
(
null
,
"输入错误"
);
}
}
}
代码
现在项目下面创建一个test.txt文件
package
oo;
import
java.io.FileReader;
import
java.util.Properties;
public
class
java {
public
static
void
main(String[]
args
) {
//创建资源文件对象
Properties
q
=
new
Properties();
try
{
//获取文件中所有的键值对,存放进行q对象
q
.load(
new
FileReader(
"test.txt"
));
}
catch
(Exception
e
) {
//
TODO
: handle exception
System.
out
.println(
"文件不存在"
);
}
//根据建得到值
String
s
=
q
.getProperty(
"name"
);
System.
out
.println(
s
);
}
}