021.3 IO流——字节流-FileInputStream读取字节
2018-06-18 01:48:37来源:未知 阅读 ()
内容:文件读取方法,读取方法例子,read(buf)方法中buf的取值,字节流缓冲区对象—提高读取速度///
文件读取方法:fis.read(),fis.read(buf),具体看例子
例子:文件读取——读取文件,显示出来
public class FileInputStreamDemo { public static void main(String[] args) { //为了确保文件一定在读之前一定存在。将字符串路径封装成File对象 File file = new File("F:"+File.separator+"eclipse_javaCode"+File.separator+"day22" +File.separator+"src"+File.separator+"demo"+File.separator+"GetMoney.java"); if(!file.exists()){ throw new RuntimeException("文件不存在!"); } //创建文件字节读取流对象 FileInputStream fis = null; try { fis = new FileInputStream(file); //第一种读取方法,单个读取 // int ch = 0; // while(ch!=-1){ // ch = fis.read(); // System.out.println(ch); //读取文件第一种方法,成功返回acsii码,失败返回-1 // } //第二个读取方法,批量读取 byte[] buf = new byte[1024]; int len = 0; while((len = fis.read(buf)) != -1){ System.out.println(new String(buf,0,len)); } } catch (IOException e) { } } }
#################################################################
一般不直接创建相应大小的字节缓冲区
缓冲区大小一般是字节的倍数,1024的倍数
public static void main(String[] args) throws IOException { File file = new File("F:\\eclipse_javaCode\\day21\\src\\day21\\shangxin.txt"); System.out.println(file.length()); //获取文件字节数 FileInputStream fis = new FileInputStream(file); System.out.println(fis.available()); //获取与之关联文件的字节数 byte[] buf = new byte[fis.available()]; //一般不会一下子创建相应大小的缓冲区,比如是高清电影就麻烦了。 //一般创建是1024的倍数 fis.read(buf); String s = new String(buf); System.out.println(s); fis.close(); }
字节流-复制文本
public static void main(String[] args) throws IOException { FileOutputStream fos = new FileOutputStream("xxx_copy.txt"); FileInputStream fis = new FileInputStream("FileInputStreamDemo.java"); byte[] buf = new byte[1024]; int len = 0; while((len = fis.read(buf))!= -1){ fos.write(buf,0,len); fos.flush(); } fis.close(); fos.close(); }
字节流的缓冲区对象
#####字节流复制文本—使用缓冲区对象,提高效率
private static void copyByBuffer() throws IOException { FileInputStream fis = new FileInputStream("aaaa.txt"); BufferedInputStream bufis = new BufferedInputStream(fis); FileOutputStream fos = new FileOutputStream("aaaa_copy.txt"); BufferedOutputStream bufos = new BufferedOutputStream(fos); byte[] buf = new byte[1024]; int by = 0; while((by = bufis.read(buf))!=-1){ bufos.write(buf,0,by); bufos.flush(); } fos.close(); fis.close(); }
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有
上一篇:Kafka分布式消息系统
- java中字节流操作(1) 2020-04-29
- Java连载96-FileInputStream方法解析、循环输出全部内容 2020-03-13
- JavaSE学习笔记(14)---File类和IO流(字节流和字符流) 2020-02-14
- 读取字节流。 2019-11-04
- java基础(23):字节流、字符流 2019-10-12
IDC资讯: 主机资讯 注册资讯 托管资讯 vps资讯 网站建设
网站运营: 建站经验 策划盈利 搜索优化 网站推广 免费资源
网络编程: Asp.Net编程 Asp编程 Php编程 Xml编程 Access Mssql Mysql 其它
服务器技术: Web服务器 Ftp服务器 Mail服务器 Dns服务器 安全防护
软件技巧: 其它软件 Word Excel Powerpoint Ghost Vista QQ空间 QQ FlashGet 迅雷
网页制作: FrontPages Dreamweaver Javascript css photoshop fireworks Flash