您的位置:首页 > 编程语言 > Java开发

java File流使用

2016-07-11 09:25 609 查看
package com.file;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

public class FileInfo {
/**
* @author zm
* @param fileName 文件名
* @throws IOException
*/
public static void printHex(String fileName) throws IOException{
FileInputStream fis=new FileInputStream(fileName);
//文件名
int b;
int i=1;
//如果等于-1结束读取
while ((b=fis.read())!=-1) {
if(b<=0xf){
System.out.print("0");
}
System.out.print(Integer.toHexString(b)+" ");
if(i++%10==0){
System.out.println();
}
}

              //关闭流
fis.close();
}
/**
* 对于大文件效率低
* @param fileName
* @throws IOException
*/
public static void printHexByByte(String fileName) throws IOException{
FileInputStream fis=new FileInputStream(fileName);
byte[] bytes=new byte[1024*8];
int byte2=0;
while ((byte2=fis.read(bytes,0,bytes.length))!=-1) {
for (int i = 0; i < bytes.length; i++) {
System.out.print(Integer.toHexString(bytes[i]& 0xff)+" ");
if(i++%10==0){
System.out.println();
}
//byte 8位 int 32 位 &0ff将高位24清零
}

}
}

}

TestFile类

package com.test;

import java.io.IOException;

import com.file.FileInfo;

public class TestFile {
/**
* @author zm
* @param args
*/

public static void main(String[] args) {
// TODO Auto-generated method stub

      try {

// FileInfo.printHex("C://test.txt");

     long start=System.currentTimeMillis();

     //开始事件

     System.out.println();

     FileInfo.printHexByByte("C://test.txt");

     long end=System.currentTimeMillis();

     System.out.println(end-start);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java class