Java_IO_实例总结(一)

来源:互联网 发布:海马助手 软件 编辑:程序博客网 时间:2024/04/28 20:23

1、字节流对文件数据的读取

/* * 演示IO读取文件数据操作 */public class IoReadTest {public static void main(String[] args) throws IOException   {//创建一个文件字节输入流FileInputStream in = new FileInputStream("D:\\test.txt");//定义一个int类型的变量,记住每次读取的一个字节int b = 0 ;while(true){b = in.read();//变量b记住每一个字节if(b==-1){//如果读取的字节为-1,表示已经读完,跳出循环break;}System.out.println(b);//否则将b打印出}in.close();}}


2、 演示将数据写入文件

/* * 演示写入文件 */public class TestWrite {//创建一个文件字节输出流public static void main(String[] args) throws IOException {FileOutputStream out = new FileOutputStream("test.txt");String str = "我爱Java!";byte[] b = str.getBytes();for(int i = 0 ;i<b.length;i++){out.write(b[i]);}}}

注意:如果通过FileOutputStream向文件中写入数据,那么该文件中的数据,先被清空,然后再写入数据。

3、演示如何将数据追加到文件末尾

/* * 演示将数据追加到文件末尾 */public class TestWrite {public static void main(String[] args) throws Exception {//创建一个文件字节输出流FileOutputStream out  = new FileOutputStream("test.txt",true);String str = "欢迎你";byte[] b = str.getBytes();for(int i = 0 ;i<b.length;i++){out.write(b[i]);}out.close();}}

注意:

通常将关闭IO操作放到finally中(固定写法):


4、文件的拷贝

/* * 演示文件的拷贝 */public class TestWrite {public static void main(String[] args) throws IOException{//创建一个字节输入流,读取当前目录下source文件夹中的mp3文件InputStream in  = new FileInputStream("d:\\source\\test.txt");//创建一个字节输出流,用于将读取的数据写入target目录下的文件中OutputStream out = new FileOutputStream("d:\\target\\test.txt");int len;//定义一个整型变量,记住每次读取的一个字节long beginTime = System.currentTimeMillis();//获取拷贝前系统的当前时间while((len= in.read())!=-1){out.write(len);//将读取的字节,写入文件}long endTime =System.currentTimeMillis();//获取拷贝后的系统时间System.out.println("拷贝文件所消耗的时间是:"+(endTime-beginTime)+"ms");in.close();out.close();}}

5、文件拷贝增强:字节流的缓冲区

public static void main(String[] args) throws IOException{//创建一个字节输入流,用于读取当前目录下scource文件夹的mp4文件FileInputStream in = new FileInputStream("D:\\source\\test.mp4");//创建一个字节出出流,用于将读入的数据写入到target文件夹中FileOutputStream out = new FileOutputStream("D:\\target\\test.mp4");//用缓冲区读写文件byte[] buff = new byte[1024];int len;//用于记录读取输入缓冲区的字节数long begintime  = System.currentTimeMillis();while((len = in.read(buff))!=-1){//判断是否读到文件末尾out.write(buff,0,len);//从第一个字节开始,向文件写入len个字节}long endtime = System.currentTimeMillis();System.out.println("拷贝文件的所需时间:"+(endtime - begintime));in.close();out.close();}




1 0