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
- Java_IO_实例总结(一)
- Java_IO_实例总结(二)
- VB数据库经典实例总结(一)
- 运放负反馈实例总结(一)
- JQuery实例总结一
- MapReduce阶段性总结实例一
- Hive阶段性总结实例一
- c++给力总结一(代码实例)
- 设计模式-行为型模式总结实例(一)
- 设计模式-结构型模式总结实例(一)
- Android自定义View总结(一)基础知识与实例
- Java Jxl Excel 操作总结4(项目实例 一)
- Java_io_流简述
- Java_io_管道流
- Java_io_数组流
- Java_IO_字节流_Reader_and_Writer
- Java_IO_文件查看
- JAVA_IO_文件读取
- A _ A
- 推荐系统工作总结-简介篇
- 单向链表的简单实现
- uml实战
- MySQL的数据文件的整理
- Java_IO_实例总结(一)
- 图片批量转换器
- 【基于QMediaPlayer的简易视频播放器】— 4、重载QSlider鼠标响应事件,实现单击跳转至任意位置
- epoll的测试用例(代码)
- Android遮罩实现图片不规则的显示
- 日语音的标准写法
- DOM操作—动态脚本
- 软件设计Solid原则学习总结
- poj2255 Tree Recovery(递归)