Java_IO_实例总结(一)
2016-07-21 18:57
537 查看
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(); }
相关文章推荐
- Description Resource Path Location Type Java compiler level does not match the version of the instal
- Intellij idea 出现错误 error:java: 无效的源发行版: 8解决方法
- java连接mysql(二)
- Java数组
- java中volatile关键字的含义
- Java反射:类名.class、class.forName()、对象.getClass区别 详解
- 以字节流读取文件时中文乱码解决
- Java_IO_Scanner类
- spring中配置quartz定时器
- java中对于页面传入ids的数组进行的批量操作
- Eclipse juno 中安装 JBoss Tools,集成Hibernate
- eclipse 常用快捷键
- Spring相关名词(0)
- javaMail邮件发送
- 学习《spring 3.x企业应用开发实战》之Spring对DAO的支持
- java实现顺序栈
- [Spring]Spring Bean的初始化 ---- getBean方法
- java.lang.IllegalArgumentException
- java爬虫爬取网页内容前,对网页内容的编码格式进行判断的方式
- RxJava 详解