android 编程新建文件格式,Android创建指定大小、类型的文件

该代码示例展示了如何使用Java创建指定大小的文件,支持KB、MB、GB单位。通过ByteBuffer和FileChannel实现文件写入,确保文件被正确填充。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.testSDcardFill;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.nio.ByteBuffer;

import java.nio.channels.FileChannel;

public class CreateFile {

public enum FileUnit {

KB, MB, GB

}

/**

* 创建指定大小和类型的文件

* @author cxq

* @param targetFile 文件路径以及文件名,需要加后缀

* @param fileLength 文件大小

* @param unit 单位,KB,MB,GB

* @retrun boolean

*/

public boolean createFile(String targetFile, long fileLength, FileUnit unit) {

//指定每次分配的块大小

long KBSIZE = 1024;

long MBSIZE1 = 1024 * 1024;

long MBSIZE10 = 1024 * 1024 * 10;

switch (unit) {

case KB:

fileLength = fileLength * 1024;

break;

case MB:

fileLength = fileLength * 1024*1024;

break;

case GB:

fileLength = fileLength * 1024*1024*1024;

break;

default:

break;

}

FileOutputStream fos = null;

File file = new File(targetFile);

try {

if (!file.exists()) {

file.createNewFile();

}

long batchSize = 0;

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);

}

if (last != 0) {

ByteBuffer buffer = ByteBuffer.allocate((int) last);

fileChannel.write(buffer);

}

fos.close();

return true;

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

if (fos != null) {

fos.close();

}

} catch (IOException e) {

e.printStackTrace();

}

}

return false;

}

}

调用:

String filePath="/sdcard/A.txt";

int fileSize=10;

createFile(filePath, fileSize, FileUnit.MB);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值