方法一:使用java 中的FileChannel类,主要用于GB大小等较大文件的创建。
/**
* create file in GB size
* @param length the number of byte in file
*/
public static void createBigFile(int length){ //1MB文件 length = 1024*1024 = 1048576
File file = new File("F:\\testBig.txt");
FileOutputStream fileOutputStream =null;
FileChannel fileChannel = null;
try{
if(!file.exists()){
file.createNewFile();
System.out.println("create");
}
fileOutputStream = new FileOutputStream(file);
fileChannel = fileOutputStream.getChannel();
fileChannel.write(ByteBuffer.allocate(1),length-1);
if(fileOutputStream!=null){
fileOutputStream.close();
}
if(fileChannel!=null){
fileChannel.close();
}
} catch (Exception e){
e.printStackTrace();
}
}
方法二:使用RandomAccessFile类,主要用于KB、MB等大小文件的创建。
/**
*create file in MB or KB size
* @param length the byte length of file
*/
public static byte[] createSmallFile(long length){ //1KB文件 length = 1024
File file = new File("F:\\testSmall.txt");
RandomAccessFile randomAccessFile = null;
byte[] bytes= null;
try {
if(!file.exists()){
file.createNewFile();
System.out.println("create new file");
}
randomAccessFile = new RandomAccessFile(file,"rw");
randomAccessFile.setLength(length);
if(randomAccessFile!=null){
randomAccessFile.close();
}
InputStream in= null;
in = new FileInputStream(file); //真正要用到的是FileInputStream类的read()方法
bytes= new byte[in.available()]; //in.available()是得到文件的字节数
in.read(bytes); //把文件的字节一个一个地填到bytes数组中
in.close(); //记得要关闭in
}catch (Exception e){
e.printStackTrace();
}
String s = new String(bytes);
return bytes;
}