文件读入和输出

读取文件:

File f = new File("e:/记事本.txt");
FileInputStream fis = new FileInputStream(f);

如果是fis.read():读取一个字节(英文)

中文是两个字节:一次读取两个字节不会出现乱码

int i = 0;
byte[] b=new byte[2];
white((i=fis.read(b))!=-1){
System.out.println(new String(b));
}

中英文混合输出记事本中内容。则读取的长度应该为整个文本的长度才不会出现乱码。

byte[] b=new byte[(int) f.length()];
int m = 0;
while((m=fis.read(b))!=-1){
System.out.print(new String(b));
}

写文件:

static void testWrite(){
FileOutputStream fos=null;
String str="hahhsbf";
try {
fos = new FileOutputStream("e:/记事本.txt");
for (int i = 0; i < str.length(); i++) {
fos.write(str.charAt(i));
}
fos.write('z');
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try {
if(fos!=null){
fos.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

但是这种写入 是覆盖文件中原来的内容!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值