灯火互联
管理员
管理员
  • 注册日期2011-07-27
  • 发帖数41778
  • QQ
  • 火币41290枚
  • 粉丝1086
  • 关注100
  • 终身成就奖
  • 最爱沙发
  • 忠实会员
  • 灌水天才奖
  • 贴图大师奖
  • 原创先锋奖
  • 特殊贡献奖
  • 宣传大使奖
  • 优秀斑竹奖
  • 社区明星
阅读:2111回复:0

IO工具类,包含很多IO有关工具方法(静态方法)

楼主#
更多 发布于:2012-09-08 09:38

package se.Day03;



import java.io.ByteArrayInputStream;

import java.io.ByteArrayOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

import java.io.OutputStream;



/** IO 工具类,包含很多IO有关工具方法(静态方法)*/

public class IOUtils {

public static Object deepCopy(Object obj){

try{

ByteArrayOutputStream buf =

new ByteArrayOutputStream();

ObjectOutputStream out = new ObjectOutputStream(buf);

out.writeObject(obj);

out.close();

byte[] data = buf.toByteArray();

ObjectInputStream in =

new ObjectInputStream(

new ByteArrayInputStream(data));

Object copy = in.readObject();

in.close();

return copy;

}catch(Exception e){

e.printStackTrace();

throw new RuntimeException();

}

  }


public static void cp(String src, String dst){

try{

InputStream in = new FileInputStream(src);

OutputStream out = new FileOutputStream(dst);

byte[] buf = new byte[2*1024];//2k byte

int n;

while((n=in.read(buf))!=-1){

out.write(buf, 0 ,n);

}

in.close();

out.close();

}catch (IOException e) {

e.printStackTrace();

throw new RuntimeException(e);

}

}

public static void cp1(String src, String dst){

try{

InputStream in = new FileInputStream(src);

OutputStream out = new FileOutputStream(dst);

int b;

while((b=in.read())!=-1){

out.write(b);

}

in.close();

out.close();

}catch (IOException e) {

e.printStackTrace();

throw new RuntimeException(e);

}

}

public static void print(File file){

try{

InputStream in = new FileInputStream(file);

int i = 1;

int b;

while((b=in.read())!=-1){

if(b<=0xf){//单位数补0

System.out.print("0");

}

System.out.println(Integer.toHexString(b)+" ");

if(i++%16==0){

System.out.println();

}

}

System.out.println();

in.close();//注意关闭哦,亲!

}catch (IOException e) {

e.printStackTrace();

throw new RuntimeException(e);

}

}

public static void print(byte[] buf){

//buf = {01000001,00001111,11010110,11010000}

int i = 1;

for(int b : buf){

b ;= 0xff;

if(b<=0xf){

System.out.print("0");

}

System.out.println(Integer.toHexString(b)+" ");

if(i++%16 == 0){

System.out.println();

}

}

System.out.println();

}

/** 将文件按照16进制输出到控制台上,每16个byte为一行*/

public static void print(String file){

try{

InputStream in = new FileInputStream(file);

int i = 1;

int b;

while((b=in.read())!=-1){

if(b<=0xf){

System.out.print("0");

}

System.out.print(Integer.toHexString(b));

if(i++%16 == 0){

System.out.println();

}

}

System.out.println();

in.close();

}catch(IOException e){

e.printStackTrace();

throw new RuntimeException(e);

}

}

}

喜欢0 评分0
游客

返回顶部