package com.test;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class MakeFile {
public static long KBSIZE = 1024;
public static long MBSIZE1 = 1024 * 1024;
public static long MBSIZE10 = 1024 * 1024 * 10;
public static void main(String[] args) {
//生成的文件路径
String path = "C:\\Documents and Settings\\Administrator\\桌面\\test.txt";
File file = new File(path);
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
//生成512字节大小文件
// createFile(file,512);
//生成1Kb大小文件
// createFile(file,1024);
//生成5Kb大小文件
// createFile(file,1024*5);
//生成10Kb大小文件
// createFile(file,1024*10);
//生成50Kb大小文件
// createFile(file,1024*50);
//生成100Kb大小文件
createFile(file,1024*100);
//生成512Kb大小文件
// createFile(file,1024*512);
//生成1Mb大小文件
// createFile(file,1024*1024);
//生成5Mb大小文件
// createFile(file,1024*1024*5);
//生成10Mb大小文件
// createFile(file,1024*1024*10);
//生成100Mb大小文件
// createFile(file,1024*1024*100);
}
public static boolean createFile(File file, long fileLength) {
FileOutputStream fos = null;
try {
if (!file.exists()) {
file.createNewFile();
}
long batchSize = fileLength;
/* batchSize = fileLength;
if (fileLength > KBSIZE) {
batchSize = KBSIZE;
}
if (fileLength > MBSIZE1) {
batchSize = MBSIZE1;
}
if (fileLength > MBSIZE10) {
batchSize = MBSIZE10;
}*/
/* long count = fileLength / batchSize;
long last = fileLength % batchSize;
fos = new FileOutputStream(file);
FileChannel fileChannel = fos.getChannel();
for (int i = 0; i < count; i++) {
ByteBuffer buffer = ByteBuffer.allocate((int) batchSize);
fileChannel.write(buffer);
}
ByteBuffer buffer = ByteBuffer.allocate((int) last);
fileChannel.write(buffer);*/
//文件内容
String str = "1";
//创建文件流
fos = new FileOutputStream(file);
//创建通道和缓冲区
FileChannel fileChannel=fos.getChannel();
ByteBuffer byteBuffer=ByteBuffer.allocate((int)batchSize);
//将字符串转化为字节数组
byte[] bytes=str.getBytes();
for(int i = 0;i<(int) batchSize;i++){
byteBuffer.put(bytes);
// int position = byteBuffer.position();
}
byteBuffer.flip();
fileChannel.write(byteBuffer);
fos.close();
return true;
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
}
这是一个Java程序,用于创建指定大小的文件。通过使用FileOutputStream和FileChannel,程序可以创建不同大小的文件,从512字节到100Mb。代码中包含了对文件大小的判断和分批写入的逻辑。
1251

被折叠的 条评论
为什么被折叠?



