package io; import java.io.FileInputStream; import java.io.IOException; public class IOUtil { /** * 讀取指定文件內容,按照16進制輸出到控制台,為什么要按十六進制? * 並且每輸出10個byte換行 * @throws IOException */ public static void printHex(String filename) throws IOException{ //把文件作為字節流進行讀操作 FileInputStream in = new FileInputStream(filename);//FileInputStream具體實現了在文件上讀取數據 int b; int i=1; while((b=in.read())!=-1)//b=in.read()這就是程序核心 { System.out.println(Integer.toHexString(b)+" ");//將整型b轉換成16進制表示的字符串?輸出 if(i++%10==0) { System.out.println();//每隔十個字節換行 } } in.close(); } }
思想就是:利用new FileInputStream(filename)把一個文件放入到一個輸入流對象in中,調用in.read()方法來逐個字節讀取(下面read源碼),讀取輸入流一個字節的數據,返回一個整型int(那么是不是十六進制的整型呢?)。
再調用Integer.toHexString(b)方法將存在b的為int的一個字節的數據轉換成一個字符串,然后輸出。
總體原理就是,將一篇字符串 放入流進行單個字節的整型讀取,然后再轉換回字符串單個輸出。
/** * Reads a byte of data from this input stream. This method blocks * if no input is yet available. * * @return the next byte of data, or <code>-1</code> if the end of the * file is reached. * @exception IOException if an I/O error occurs. */ public int read() throws IOException { return read0(); } private native int read0() throws IOException;
//把文件作為字節流進行讀操作
FileInputStream in = new FileInputStream(filename);//FileInputStream具體實現了在文件上讀取數據