java 以字节为单位读取文件(2)
2016-02-22 21:10
537 查看
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; public class readFile2 { /** * 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。 * @param fileName */ public static void readFileByBytes(String fileName) { File file = new File(fileName); InputStream in = null; try { System.out.println("以字节为单位读取文件内容,一次读一个字节:"); // 一次读一个字节 in = new FileInputStream(file); int tempbyte; while ((tempbyte = in.read()) != -1) { System.out.write(tempbyte); } System.out.write(10); //当字符串中含有'\n'时会刷新out,'\n'的ascii码为10 //如果字符串中没有'\n',待读取文件的最后一行将无法打印 in.close(); } catch (IOException e) { e.printStackTrace(); return; } try { System.out.println("以字节为单位读取文件内容,一次读多个字节:"); // 一次读多个字节 byte[] tempbytes = new byte[100]; int byteread = 0; in = new FileInputStream(fileName); // 读入多个字节到字节数组中,byteread为一次读入的字节数 while ((byteread = in.read(tempbytes)) != -1) { System.out.write(tempbytes, 0, byteread); } } catch (Exception e1) { e1.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e1) { } } } } public static void main(String[] args) { // TODO Auto-generated method stub String filePath="F:\\test\\testR.txt"; //在F盘创建test文件夹,在文件夹下创建testR.txt文件 readFileByBytes(filePath); } }
相关文章推荐
- Eclipse配置外部Maven
- JAVA_面向对象_笔记_01
- JAVA_面向对象_笔记_01
- Spring定时任务的几种实现
- java的动态代理机制详解
- eclipse ant jacoco
- JavaWeb----Struts2
- 堆排序-java
- Java
- Java IO 之File类
- HDU Exponentiation 1063 Java大数题解
- Java-final
- LeetCode29DivideTwoIntegers--In Java
- Spring.Net学习笔记(二)-数据访问器
- java中静态代码块的用法 static用法详解
- Spring源代码解析 ---- 循环依赖
- Android开发遇到eclipse运行程序时报timeout
- 【转】一个不错的eclipse反编译插件
- 第一个Java程序——HolloWorld
- Java多线程Lock对象之ReentrantLock(1)