首先是二进制读取文件成为字节的代码
package com.bird.thinking;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* @use 读取二进制文件
* @author Bird
*
*/
public class BinaryFile {
public static byte[] read(File bFile) throws FileNotFoundException{
BufferedInputStream bf = new BufferedInputStream(new FileInputStream(bFile));//构建读取流
try{
byte[] data = new byte[bf.available()];//构建缓冲区
bf.read(data);
return data;
} catch (IOException e) {
throw new RuntimeException(e);//改变成运行时异常
}finally{
try {
bf.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
public static byte[] read(String bFile) throws FileNotFoundException{//重载构造方法
return read(new File(bFile).getAbsoluteFile());
}
public static void main(String [] args) throws FileNotFoundException{
for(byte a: read("d://book.xml"))
System.out.print(a);
}
}
下面是包装JAVA的控制台输入实现回显功能
package com.bird.thinking;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* @use 从控制台输入并且回显
* @author Bird
*
*/
public class Echo {
public static void main(String [] args) throws IOException{
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));//将输入流包装成BufferedReader
String s = null;
while((s = stdin.readLine()) != null && s.length() !=0){
System.out.println(s);
if(s.equals("exit"))
break;
}
}
}
下面是使用NIO包的通道功能读取并且写入文件,并在文件的末尾追加内容
package com.bird.thinking;
import java.io.FileOutputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/**
* @use 新nio包的通道读取文件
* @author Bird
*
*/
public class GetChannel {
public static void main(String [] args) throws Exception{
FileChannel fc = new FileOutputStream("d://bird.txt").getChannel();//建立读取通道
fc.write(ByteBuffer.wrap(BinaryFile.read("d://book.xml")));//获得字节流并且通过通道写入
fc.close();
Thread.sleep(500);//等待磁盘写入数据完毕
fc = new RandomAccessFile("d://bird.txt","rw").getChannel();//随机读取,对文件末尾追加内容
fc.position(fc.size());//调整文件指针的位置到文件的末尾
fc.write(ByteBuffer.wrap("哥再加一点".getBytes()));//在文件末尾加入这几个字
fc.close();
}
}
下面是对文件的复制
package com.bird.thinking;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/**
*
* @author Bird
* @use 文件的复制
*/
public class ChannelCopy {
private static final int BSIZE = 1024;//文件缓冲字节区,大小可以自己定
public static void main(String [] args) throws IOException{
FileChannel in = new FileInputStream("d://book.xml").getChannel();//得到输入通道
FileChannel out = new FileOutputStream("d://bird.xml").getChannel();//得到输出通道
ByteBuffer buffer = ByteBuffer.allocate(BSIZE);//设定缓冲区
while(in.read(buffer) != -1){
buffer.flip();//准备写入,防止其他读取,锁住文件
out.write(buffer);
buffer.clear();//准备读取。将缓冲区清理完毕,移动文件内部指针
}
}
}