TypechoJoeTheme

IT技术分享

统计

JAVA中的IO操作

2015-05-16
/
0 评论
/
708 阅读
/
正在检测是否收录...
05/16

IO又可写作I/O,是In和Out的首字母缩写,即输入和输出。

根据数据的走向分为:输入流和输出流;

根据数据的类型分为:字节流和字符流。

字节流可以处理所有类型的数据,包括文本,图像,音频,视频等。对应的Java类都是以Stream结尾的。

字符流只可处理文本类型的数据,并且与编码密切相关,读到一个和多个字节时,根据编码装换成对应的字符。对应的Java类都是以Reader和Writer结尾的。

一、使用FileInputStream和FileOutputStream字节流拷贝文件

FileInputStream fis = new FileInputStream("file.txt");

FileOutputStream fos = new FileOutputStream("copyFile.txt");

byte[] input = new byte[1024];

where(fis.read(input) != -1){

    fos.write(input);

}

fos.close();

fis.close();

二、使用BufferedInputStream和BufferedOutputStream缓冲字节流拷贝文件

FileInputStream fis = new FileInputStream("file.avi");

BufferedInputStream bis = New BufferedInputStream(fis);

FileOutputStream fos = new FileOutputStream("copyFile.avi");

BufferedOutputStream bos = New BufferedOutputStream(fos);

byte[] input = new byte[1024];

where(bis.read(input) != -1){

    bos.write(input);

}

bis.close();

fis.close();

bos.close();

fos.close();

三、使用InputStreamReader语OutputStreamWriter字符流读写文件数据

FileInputStream fis = new FileInputStream("file.txt");

InputStreamReader isr = new InputStreamReader(fis,"UTF-8");

FileOutputStream fos = new FileOutputStream("copyFile.txt");

OutputStreamWriter osw = new OutputStreamWriter (fos ,"UTF-8");

char[] input = new char[1024];

int n = 0;

where((n = isr.read(input)) != -1){

    osw.write(input,0,n);

}

isr.close();

fis.close();

osw.close();

fos.close();

四、使用BufferedReader语BufferedWriter缓冲字符流读写文件数据

FileInputStream fis = new FileInputStream("file.txt");

FileOutputStream fos = new FileOutputStream("copyFile.txt");

InputStreamReader isr = new InputStreamReader(fis,"UTF-8");

OutputStreamWriter osw = new OutputStreamWriter (fos ,"UTF-8");

BufferedReader br = new BufferedReader(isr);

//BufferedWriter br = new BufferedWriter (osw);

PrintWriter pw = new PrintWriter(osw,true);//true表示强制flash

String input = "";

while((input = br.readLine()) != null){

    // bw.write(input+"\n");

    pw.println(input);

}

br.close();

//bw.flash();

//bw.close();

pw.close();

isr.close();

fis.close();

osw.close();

fos.close();

五、将FileReader与FileWriter包装为缓冲流进行文件拷贝

FileReader fr = new FileTeader("file.txt");

BufferedReader br = new BufferedReader(fr);

FileWriter fw = new FileWriter("coppyFile.txt");

BufferedWriter bw = new BufferedWriter(fw);

String input = "";

while((input = br.readLine()) != null){

    bw.write(input+"\n");

}

bw.flash();

bw.close();

fw.close();

br.close();

fr.close();

六、使用RandomAccessFile随机读写文件

RandomAccessFile raf = new RandomAccessFile(file,"rw");

int start = 100;

String str = "This is a test !"

raf.seek(start);

raf.writeBytes(str);

byte[] input = new byte[1024];

raf.read(input);
朗读
赞 · 0
版权属于:

IT技术分享

本文链接:

https://idunso.com/archives/72/(转载时请注明本文出处及文章链接)