- 26
- 0
- 约5.98千字
- 约 6页
- 2017-06-12 发布于北京
- 举报
文件输入与输出以流的形式进行,同时根据内容不同分为字节和字符两种
字节流的读取与写入
读取步骤:File→FileInputStream→f.read(bytes)
写入步骤:File→FileOutputStream→f.write(bytes)
演示:读取字节文件即把字节从文件读到内存中
File f=null;//定义文件类的变量,并为空
f=new File(“”);//给变量赋值,表明指向某个文件
因为File没有读写的能力,所以需要用个InputStream
Try{
FileInputStream fis=null;//定义文件字节输入流变量
fis=new FileInputStream(f);//给其赋值,指向目标文件
Byte [] bytes=new byte[1024]; //定义数组,把字节流的字节读到数组中,相当于缓存
Int n=0;//记录读取的字节数
While(n=fis.read(bytes)==-1){//以1024字节大小为单位每次读取字节,从fis字节流中,并放到bytes字节组中,读取字节个数为零即读到末尾,则返回数值-1.
String s=new String(bytes,0,n);// 把字节转换成字符串,0代表:转换开始的下标;n代表:转换字节的长度。
System.out.println(s);//把字符串打印到显示器上
}
}
演示:写入字节文件即把字节从内存中写道文件里
File f=null;
f=new File(“d:\\ss.txt”);
FileOutputSteam fos=null;
Try{
Fos=new FileOutputStrream(f);
String s=” ”;//定义空字符串
Byte []bytes=new byte[1024];//定义字节数组,存储转换来的字符
Fos.write(s.getBytes());//把String转化为byte
}
举例:图片的拷贝即从一个磁盘拷贝到另一个磁盘;或从一个电脑到另一个电脑
思路:先把图片读到内存,在写入到某个文件里,因为图片是二进制文件,则只能用字节流
File f1=new File(“c:\\a.jpg”);
FileInputStream fis=null;
Fis=new FileInputStream(f1) ;
File f2=new File(“d:\\a.jpg”);
FileOutputStream fos=null;
Fos=new FileOutputStream(f2);
Byte buf[]=new byte[1024];
Int n=0;//记录实际读到的字节数
While((n=fis.read(buf))!==-1){//以buf的大小为单位读取fis文件里的字节,读到内存buf字节组中。N代表一次读的字节的个数,当没有读到字节时,n的返回数值是-1.
Fos.write(buf);
}
字符的读取和写入
文件字符流:FileReader→f.read(c);
FileReader→BufferedReader→f.readLine();
File→FileReader→BufferedReader→reader.readLine();
同理: FileWeader→f.write(c);
FileWeader→BufferedWriter→f.write();
File→FileWeader→BufferedWriter→reader.write();
文件读取字符流对象
FileReader fr=null;//写入到文件
FileWriter fw=null;
Try{
Fr=new FileReader(“c:\\test.txt”);//创建输出对象
Fw=new FileWriter(“d:\\vvv.txt”);
Int n=0;//记录实际读取的字符数
Char c[]=new char[1024];//定义字符数组,来存放从文件读取的字符
While((n=fr.read(c))!==-1){
String s=new String(c,0,n);//把字符数组转换为字符串
System.out.println(s);
System.out.println(c);
Fw.write(c);//将字符写入到d盘指定的文件
}
}
第二种:
BuffereReader br=null;
bufferedWriter bw=null;
Try{
//先创建FileReader对象,然后再升级为bufferedReader
//先通过
原创力文档

文档评论(0)