Java写一个200M的文件要多久_java如何更快生成00000000~99999999的8位数字保存到文件中?...

你的问题在于把所有的事情放在一起做了,这样可能效率高一点,但其实并不高,而且会变慢,尤其是把显示和生成数据合并了,这样每次生成数据再同时生成字符串,这样就会很慢。不妨分成两步三个方法:1.计算出随机数,2.格式化并写入文本文件。

public int GetRandomNum(object max)

{

int result = 0;

Random r = null; int seed = 0; byte[] bt = null;

try

{

bt = Guid.NewGuid().ToByteArray();

seed = BitConverter.ToInt32(bt, 0);

r = new Random(seed);

result = r.Next(Convert.ToInt32(max));

}

catch (Exception)

{

throw;

}

return result;

}

public void WriteRandomNumToFile(string path,Dictionary nums)

{

List strs = null;

string content = string.Empty;

DirectoryInfo dir = null;

try

{

onMsgOut(string.Format("开始将字典转为列表"));

strs = (from v in nums select string.Format("{0}", v.Value)).ToList();

onMsgOut(string.Format("开始组装数据"));

content = string.Join("\r\n", strs.ToArray());

if(!(dir=new FileInfo(path).Directory).Exists)

{

dir.Create();

}

onMsgOut(string.Format("正在将随机数写入文件:{0}", path));

File.WriteAllText(path, content);

onMsgOut(string.Format("写入文件成功"));

}

catch (Exception ex)

{

onError?.Invoke(ex);

}

}

public Dictionary GetRandomNums(int num,int max)

{

Dictionary result = null;

int n = 0, total = 0;

bool continued = true;

try

{

total = num;

result = new Dictionary();

while (0 < num--)

{

continued = true;

onMsgOut(string.Format("开始第{0}次生成随机数,总计:{1}", total - num, total));

//加载字典为防止生成重复

while (continued)

{

if (!result.ContainsKey(n = GetRandomNum(max)))

{

onMsgOut(string.Format("生成随机数:{0:D8}", n));

result.Add(n, string.Format("{0:D8}", n));

continued = !continued;

}

else

{

onMsgOut(string.Format("此随机数已经存在:{0:D8}将重新生成", n));

}

}

}

}

catch (Exception ex)

{

onError?.Invoke(ex);

}

return result;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值