随笔 - 0, 文章 - 75, 评论 - 0, 引用 - 0
数据加载中……

IO

读写文件:



字节流——图片、mp3、影音


字符流——文本


首先介绍字符流:


public static void main(String[] args) throws Exception
{
Reader rd=null; //读
Writer
wt=null; //写
try
{
rd=new FileReader("pet.template"); //读取pet.template文件内容
char[]
cr = new char[1];
int
length=rd.read(cr); //取得内容长度
StringBuffer str=new
StringBuffer();
while(length!=-1){ //长度为-1则无数据
str.append(cr);
length=rd.read(cr);
}
wt=new
FileWriter("f:\\a.txt"); //在f盘创建a.txt
wt.write(str.toString()); //并写入数据
System.out.println(str.toString());
}
catch (Exception e) {
}finally{
try
{
if(rd!=null)
rd.close();
//一定要关闭文件流
if(wt!=null)
wt.close();
//..
} catch
(Exception e2) {
}
}



字节流:


InputStream imput=new
FileInputStream("Sunset.jpg"); //读取Sunset.jpg图片
FileOutputStream
output=new FileOutputStream("f:\\a.jpg"); //要输出的位置
byte[]
img=new byte[imput.available()];
int
length=imput.read(img); //读取img长度
output.write(img);
//把图像写入f:\a.jpg
imput.close();
output.close();

posted on 2012-04-22 15:32 hantai 阅读(1255) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航: