62,614
社区成员
发帖
与我相关
我的任务
分享
FileWriter f=new FileWriter("D:/data.txt");
BufferedWriter buf=new BufferedWriter(f,1024*512);
int o=0;
while(o<10000){
int []array=new int[100000];
for(int i=0;i<array.length;i++)
array[i]=(int) (Math.random()*1000000);
int j=0;
while(j<array.length){
buf.write(String.valueOf(array[j]));
System.out.println(array[j]);
j++;
}
o++;
}
buf.close();
byte[] bytes = int2bytes(-1234);
int x = bytes2int(bytes);
System.out.println(x);
>>>public static void main(String[] args) throws Exception {
long startTime = System.currentTimeMillis();
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("c:/test.dat"));
Random rad = new Random();
long i = 0;
while (i < 1000000000) {
bos.write(int2bytes(rad.nextInt()));
i++;
}
bos.flush();
bos.close();
System.out.println(System.currentTimeMillis() - startTime);
}
static int bytes2int(byte[] b) {
return b[0] << 24 + b[1] << 16 + b[2] << 8 + b[3];
}
static byte[] int2bytes(int i) {
byte[] rs = new byte[4];
rs[0] = (byte) (i >> 24);
rs[1] = (byte) (i >> 16);
rs[2] = (byte) (i >> 8);
rs[3] = (byte) (i);
return rs;
}
耗时69217ms,文件大小3.72 GB (4,000,000,000 字节),占用空间3.72 GB (4,000,002,048 字节),不写硬盘耗时11419ms。
final int n = 100;
final int max = 1000000000;
File file = new File("D:/data.dat");
DataOutputStream dos = null;
try {
dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(
file)));
for (int i = 0; i < n; i++) {
int x = (int) (Math.random() * max);
System.out.println(x);
dos.writeInt(x);
}
} finally {
if (dos != null) {
try {
dos.close();
dos = null;
} catch (Exception ex) {
}
}
}
System.out.println("==========以下为读取===========");
DataInputStream dis = null;
try {
dis = new DataInputStream(new BufferedInputStream(new FileInputStream(
file)));
for (int i = 0; i < n; i++) {
int x = dis.readInt();
System.out.println(x);
}
} finally {
if (dis != null) {
try {
dis.close();
dis = null;
} catch (Exception ex) {
}
}
}
static void t8(){
byte[] buff = new byte[512];//4*128//128个int
Random rand = new Random(System.currentTimeMillis());
rand.nextBytes(buff);
OutputStream out = null;
try{
out = new FileOutputStream("c:\\test1.data");
long l = System.currentTimeMillis();
for(int i=0,end=10000*10000*10; i<end; i+=128){
out.write(buff, 0, 512);
out.flush();
}
System.out.println(System.currentTimeMillis()-l);
out.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
这个测试结果:
写入:3.72 GB (4,000,002,048 字节)
耗时:125734
我估计 我机器上java 写硬盘速度就这样了。