读取配置文件并读取文件

配置文件

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();

}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值