/**
* 顺序打印1到最大的n位数,比如输入3,打印1,2,3,~直到999 有问题
*
* @author Administrator
*
*/
public class Problem12 {
public static void main(String[] args) {
Problem12 p12 = new Problem12();
p12.printToMaxOfNDigts(9);
}
private void printToMaxOfNDigts(int n) {
// 学习StringBuffer
StringBuffer sb = new StringBuffer("1");
BigDecimal maxValue = new BigDecimal(0);
if (n == 0) {
System.out.println(0);
} else {
// 记下每次扩展的倍数
for (int i = 1; i <= n; i++) {
sb.append(0);
}
if (sb != null) {
maxValue = BigDecimal.valueOf(Long.valueOf(sb.toString()));
}
}
String fileName = "E:\\num.txt";
String fileName2 = "E:\\num2.txt";
String fileName3 = "E:\\num3.txt";
{
long time = System.currentTimeMillis();
printIntoFile(maxValue, fileName);
System.out.println("printIntoFile use time: " + (System.currentTimeMillis() - time) + "ms");
}
{
long time = System.currentTimeMillis();
printIntoFileMethod2(maxValue, fileName2);
System.out.println("printIntoFileMethod2 use time: " + (System.currentTimeMillis() - time) + "ms");
}
{
long time = System.currentTimeMillis();
printIntoFileMethod3(maxValue, fileName3);
System.out.println("printIntoFileMethod3 use time: " + (System.currentTimeMillis() - time) + "ms");
}
}
private void printIntoFileMethod3(BigDecimal maxValue, String fileName) {
RandomAccessFile randomFile = null;
try {
randomFile = new RandomAccessFile(fileName, "rw");
long fileLength = randomFile.length();
// randomFile.seek(fileLength);
// 打印出需要的位数数字
for (BigDecimal b = new BigDecimal(1); b.compareTo(maxValue) < 0; b = b.add(new BigDecimal(1))) {
randomFile.writeBytes(b.toString() + "\r\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (randomFile != null) {
try {
randomFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private void printIntoFileMethod2(BigDecimal maxValue, String fileName) {
BufferedWriter out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName, true)));
// 打印出需要的位数数字
out.flush();
for (BigDecimal b = new BigDecimal(1); b.compareTo(maxValue) < 0; b = b.add(new BigDecimal(1))) {
out.write(b.toString() + "\r\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void printIntoFile(BigDecimal maxValue, String fileName) {
File file = new File(fileName);
if (file.exists()) {
file.delete();
}
FileWriter fw = null;
PrintWriter pw = null;
try {
fw = new FileWriter(file, true);
pw = new PrintWriter(fw);
fw.flush();
pw.flush();
// 打印出需要的位数数字
for (BigDecimal b = new BigDecimal(1); b.compareTo(maxValue) < 0; b = b.add(new BigDecimal(1))) {
pw.write(b.toString() + "\r\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fw != null || pw != null) {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
pw.close();
}
}
}
}
5位数 673kb
缓冲写入最快77ms
7位数 86806kb 85mb
缓冲写入最快77ms
9位数 10800000kb 10gb
缓冲写入最快201978ms