一、用字节流读写文件
1、写文件
//字节流向文件中写东西
public static void main(String[] args) throws IOException{
String name="D:"+File.separator+"sun.txt";
File f=new File(name);
OutputStream ou=new FileOutputStream(f);
String str="红鲤鱼与绿鲤鱼与驴,我是字符流";
byte[] b=str.getBytes();//字节流
try {
ou.write(b); //输出流
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
ou.close();
}
}
2、读文件
//用字节流读取文件内容
public static void main(String[] args) throws IOException{
String name="D:"+File.separator+"sun.txt";
File f=new File(name);
InputStream in=new FileInputStream(f);
byte[] b=new byte[100];
in.read(b);
in.close();
System.out.println(b);
System.out.println(new String(b));
}
二、用字符流读写文件
1、写文件
//字符流写入内容到文本
public static void main(String[] args) throws IOException {
String name="D:"+File.separator+"sun1.txt";
File f=new File(name);
Writer o =new FileWriter(f);
String str="红鲤鱼与绿鲤鱼与驴,我是字符流";
o.write(str);
o.close();
}
2、读文件
//用字符流读取内容
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String name="D:"+File.separator+"sun1.txt";
File f=new File(name);
char[] ch=new char[100];
Reader rd=new FileReader(f);
rd.read(ch);
rd.close();
System.out.println(ch);
System.out.println(new String(ch));
}
字符流-字节流
1、字节(byte)是计算机存储数据最小单位,以进制存储。一个汉字占两个字节。
2、字符(char)是计算机使用过程中的符号或英文或数字或汉字。
3、用字节流没有缓冲区,用字符流有缓冲区。(不能马上看到效果)
4、用字符流写,不关闭缓冲流,写不进去。
5、字符流效率高一些,字节流效率低一些。因磁盘中的数据文件都是用字节存储的,一般开始时,字节流更广泛。