Java讀取本地文件的兩種方法及其區別

<span style="font-size:32px;">代碼如下:</span>


<span style="font-size:18px;">package TestDemo;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
//批量讀取
public class InputDemo1 {	
	
	//數組必須足夠大
	public static  void  p1(String  fileName) throws IOException{
		File file1= new  File(fileName);
		FileInputStream fis= new  FileInputStream(file1);
		byte[] byte1=new  byte[20*1024*1024];//byte數組必須足夠大,不然無法讀取完全
		int b=fis.read(byte1, 0, byte1.length);
		
		int temp=1;
		for(int i=0;i<b;i++){
			
			System.out.print(Integer.toHexString(byte1[i]&0xff)+"  ");
			if(temp++%10==0){
				
				System.out.println();
			}
		}
		
		fis.close();		
	}	
	
	//無論數組是否足夠大,都可以讀取完全
	public static void  p2(String fileName) throws IOException{
		
		File file2= new  File(fileName);
		FileInputStream fis2=new  FileInputStream(file2);
		byte[] byte2=new  byte[20];
		int k=0;
		int temp2=1;
		while((k=fis2.read(byte2, 0, byte2.length))!=-1){
			
		for (int i = 0; i <k; i++) {
			
			System.out.print(Integer.toHexString(byte2[i]&0xff)+" ");
			if(temp2++%10==0){
				
				System.out.println();				
			}
		}						
		}
		
		
		
		fis2.close();		
	}
	public static void main(String[] args) {
		try {
			long start=System.currentTimeMillis();
			//p1("E:\\JavaWeb.zip");
			p2("E:\\JavaWeb.zip");
			long end=System.currentTimeMillis();
			System.out.println((start-end)+"ms");
		} catch (IOException e) {
			
			// TODO Auto-generated catch block
			
			e.printStackTrace();
		}
	}

}
</span>

發佈了34 篇原創文章 · 獲贊 11 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章