本文主要是介绍JAVA学习随笔(6)--FileInputStream随笔,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.字节流
1)InputStream抽象了应用程序读取数据的方式
OutputStream抽象应用程序写出数据的方式
2)EOF = End 读到-1就读到结尾
3)输入流基本方法
int b = in.read();//读取一个字节无符号填到int低8位
in.read(byte[] buf);
in.read(byte[] buf,int start,int end);
4)输出流基本方法,和输入流类似
out.write(int b);
out.write(byte[] buff);
out.write(byte[] buf,int start,int size);
package file;import java.io.FileInputStream;
import java.io.IOException;public class IOUtil { public static void printHex(String fileName) throws IOException{FileInputStream in = new FileInputStream(fileName);int b;int i = 1;while((b = in.read()) != -1){if(b <= 0xf){System.out.print("0" + Integer.toHexString(b) + " ");}else{System.out.print(Integer.toHexString(b) + " ");}if(i++ % 10 == 0){System.out.println();}}in.close();}}
package file;import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;public class IOUtil { public static void printHex(String fileName) throws IOException{FileInputStream in = new FileInputStream(fileName);int b;int i = 1;while((b = in.read()) != -1){if(b <= 0xf){System.out.print("0" + Integer.toHexString(b) + " ");}else{System.out.print(Integer.toHexString(b) + " ");}if(i++ % 10 == 0){System.out.println();}}in.close();}public static void printHexByByteArray(String fileName) throws IOException{FileInputStream in = new FileInputStream(fileName);//最大缓存设20KBbyte[] buf = new byte[20*1024];//返回的是读到的字节数int bytes = in.read(buf,0,buf.length);int flag= 1;for(int i=0;i<bytes;i++){if(buf[i] < 0xf){System.out.print("0" + Integer.toHexString(buf[i]) + " ");}else{System.out.print(Integer.toHexString(buf[i]) + " ");}if(flag++ % 10 == 0){System.out.println();}}in.close();}}
单字节读取不适合读比较大的文件,文件数据量上去后单字节读取方式时间消耗更大。批量读取是最常见的读取文件方式
package file;import java.io.IOException;public class IOUtilTest02 {public static void main(String[] args) throws IOException {// TODO Auto-generated method stublong start = System.currentTimeMillis();IOUtil.printHexByByteArray("e:\\javaio\\111.mp3");long batchEnd = System.currentTimeMillis();IOUtil.printHex("e:\\javaio\\111.mp3");long aloneEnd = System.currentTimeMillis();System.out.println("单独读取耗时:" + (aloneEnd - batchEnd));System.out.println("批量读取耗时:" + (batchEnd - start));}}
5)FileOutputStream–实现向文件中写出byte数据的方法
public class FileOutDemo1{public static void main(String[] args) throws IOException {//如果文件不存在,则直接创建,如果存在则删除后创建FileOutputStream out = new FileOutputStream("e://javaio//out.txt");out.write('A');//写出'A'的低8位int a = 10;out.write(a >>> 24);out.write(a >>> 16);out.write(a >>> 8);out.write(a);byte[] buf = "张小红".getBytes("gbk");out.write(buf);out.close();}
}
这篇关于JAVA学习随笔(6)--FileInputStream随笔的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!