Java5_2_文件流_字节流_FileInputStream与FileOutputStream由刀豆文库小编整理,希望给你工作、学习、生活带来方便,猜你可能喜欢“文件流类与文件流对象”。
一:FileInputStream
/*
* 作者:田停
* 日期:2013 8 19
* 功能:文件的读取(FileInputStream类的使用演示)(在磁盘中已存在)*/
package com.tt.IO;
import java.io.*;
public cla Demo2 {
/**
* @param args
*/
public static void main(String[] args){
// TODO Auto-generated method stub
File f=new File(“d:aa.txt”);
//因为File没有读写的能力,所以需要借助FileInputStream来try {
FileInputStream fis=new FileInputStream(f);
//定义一个字节数组
byte []bytes=new byte[1024];
int n=0;//得到实际读取到的字节数
//循环读取,读完n=-1
while((n=fis.read(bytes))!=-1)
{
//把字节转成String
String s=new String(bytes,0,n);
System.out.println(s);
}
fis.close();
} catch(Exception e){
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
二:FileOutputStream
/*
* 作者:田停
* 日期:2013 8 19
* 功能:FileOutputStream
*/
package com.tt.IO;
import java.io.*;
public cla Demo3 {
/**
* @param args
*/
public static void main(String[] args){// TODO Auto-generated method stubFile f=new File(“d:t1.txt”);
FileOutputStream fos=null;
try {
fos=new FileOutputStream(f);
String s=“中国你好!”;
fos.write(s.getBytes());
} catch(Exception e){
// TODO Auto-generated catch blocke.printStackTrace();
}
}
}
三:图片的拷贝
/*
* 作者:田停
* 日期:8 20
* 功能:图片的拷贝
*/
package com.tt.IO;
import java.io.*;
public cla Demo4 {
public static void main(String[] args){// TODO Auto-generated method stub
FileInputStream fis=null;
}} FileOutputStream fos=null;try {fos=new FileOutputStream(“d:shuihu_1.jpg”);fis=new FileInputStream(“c:shuihu_1.jpg”);int byte []bytes=new byte[1024];while((n=fis.read(bytes))!=-1){//输出流指定文件fos.write(bytes);}} catch(Exception e){// TODO Auto-generated catch blocke.printStackTrace();} finally {try {fos.close();fis.close();} catch(IOException e){// TODO Auto-generated catch blocke.printStackTrace();} }