url=/Users/z_ten/Documents
name=myfile.txt
url是读写文件的文件地址,name是读写文件的文件名称
代码:
FileInputStream is=null;
try {
is = new FileInputStream("my.properties");//配置文件名称:my.properties
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
Properties pt=new Properties();
try {
pt.load(is);
is.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
在程序中读写配置文件使用输入流将配置文件信息读到程序中,再定义一个properties类型的pt去装填该对象。load方法,不是=。之后关闭输入流。
写文件:
File file=new File(pt.getProperty("url"),pt.getProperty("name"));//要写入文件的文件位置和名称,此处是读取配置文件中的内容得到的。
try {
file.createNewFile();//若没有该文件,则创建一个。
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String str=" hello word1";//要写入文件的内容
byte bt[] = new byte[1204];
bt=str.getBytes();
try {
FileOutputStream in = new FileOutputStream(file,true);//如果是true表示不覆盖原文件,若是不写,则表示覆盖原文件
try {
in.write(bt, 0, bt.length);//将bt中的内容从第零位开始写入文件,写的长度为bt的长度。
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
in.close();//关闭流
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
读文件:
File file=new File(pt.getProperty("url"),pt.getProperty("name"));//要读取的文件的地址和名称(同上写文件)
try {
FileInputStream in = new FileInputStream(file);//定义一个流去获取文件里的内容。
InputStreamReader is=new InputStreamReader(in);//定义一个流去将获取文件的流中的内容。
//此时流中的数据其实不是文件中的原文内容,而是原文内容对应的编码值。所以用int去接受
int ch=0;
try {
while((ch=is.read())!=-1){//判断is流中是否已经读取完成
System.out.print((char)ch);//将对应的编码值转化为对应的内容并且打印出来。
}
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}