背景:文件的写入、读取是几本的操作,有时候io是系统的瓶颈,因此使用nio写入可以提高系统的性能
package rememberSet;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
public class FileUtils {
/**
* 读取指定文件大小的字节数
* @param fileName
* @param from
* @param to
* @return
*/
public static byte[] readFile(String fileName, long from, long to) {
FileChannel channel = null;
byte[] data = new byte[(int) (to - from)];
try {
channel = new RandomAccessFile(fileName, "r").getChannel();
MappedByteBuffer byteBuffer = channel.map(MapMode.READ_ONLY, from, to - from);
for (int i = 0; i < to - from; i++) {
data[i] = byteBuffer.get();
}
} catch (Exception e) {
}
return data;
}
/**
*读取文件的字节数
* @param fileName
* @return
*/
public static long readBytes(String fileName) {
byte[] data = new byte[4096];
long readBytes = 0;
InputStream is = null;
int n = 0;
try {
is =new FileInputStream(fileName);
while ((n = is.read(data)) != -1) {
readBytes += n;
}
} catch (Exception e) {
} finally {
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
}
}
return readBytes;
}
/**
* 将字符串写入到文件中
* @param fileName
* @param content
* @param characterCoding
*/
public static long writerToFile(String fileName,String content,String characterCoding){
OutputStreamWriter os=null;
try {
os=new OutputStreamWriter(new FileOutputStream(fileName,true),characterCoding);
os.write(content);
os.flush();
} catch (UnsupportedEncodingException e) {
} catch (FileNotFoundException e) {
} catch (IOException e) {
}finally{
try {
if (os != null) {
os.close();
}
} catch (IOException e) {
}
}
System.out.println(Thread.currentThread().getName()+"写入:"+content.getBytes().length);
return content.getBytes().length;
}
public static void main(String[] args) throws UnsupportedEncodingException {
writerToFile("Desktop/aa","我爱你中国","UTF-8");
long readBytes = readBytes("/Users/yy/Desktop/aa");
System.out.println(readBytes);
byte[] data = FileUtils.readFile("Desktop/aa", 0l, readBytes);
String s = new String(data,"UTF-8");
System.out.println(s);
}
}