最近面試某某公司測(cè)試工程師的時(shí)候遇到的一個(gè)編程筆試題,如下
請(qǐng)生成 test1@126.com 123456 到 test5000@126.com 123456 的5000個(gè)郵箱賬號(hào),換行展示并保存在test.txt文件中,可編程實(shí)現(xiàn),也可使用其它方法,即:
test1@126.com 123456
test2@126.com 123456
......
test5000@126.com 123456
編程方面,我基本用的是Java和shell,那我這里就用java和shell兩種方式實(shí)現(xiàn)
解法一:Java
思路:這個(gè)題用Java來(lái)寫(xiě),可以說(shuō)比較簡(jiǎn)單,題目的變動(dòng)就只有1-5000這幾個(gè)數(shù)字,另外就是實(shí)現(xiàn)換行和輸出到test.txt文件中,就需要用到大概三點(diǎn),變量、異常捕捉、輸出流。變量主要實(shí)現(xiàn)1-5000,輸出流實(shí)現(xiàn)輸出字符到test.txt文件中,異常捕捉在這里作用就是捕捉輸出流IO異常,變量、異常捕捉、IO都是自動(dòng)化測(cè)試中經(jīng)常需要用到的內(nèi)容,代碼如下
import java.io.*;
public class Email {
public static void main(String args[])
{
// 獲取當(dāng)前工作空間路徑
String dir = System.getProperty("user.dir");
// 設(shè)置test.txt文件路徑
String path = dir + "\\test.txt";
// System.out.print(path);
File file = new File(path);
if (!file.exists()) {
// try、catch實(shí)現(xiàn)異常捕捉
try {
// 如果文件不存在,創(chuàng)建文件
file.createNewFile();
// FileOutputStream fileOutputStream = new FileOutputStream(file , true);
// Writer writer = new OutputStreamWriter( fileOutputStream);
FileWriter fileWriter = new FileWriter(path,true);
// 變量i實(shí)現(xiàn)1-5000
for ( int i = 1 ; i <= 5000 ; i++ )
{
// writer.write("test" + i + "@126.com 123456\n");
// 把字符輸出到test.txt文件末尾
fileWriter.append("test" + i + "@126.com 123456\n");
}
// writer.close();
// fileOutputStream.close();
// 每次寫(xiě)文件結(jié)束,都要關(guān)閉輸出流
fileWriter.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
解法二:shell
思路:換成是shell script實(shí)現(xiàn)就更簡(jiǎn)單了,代碼縮減了一大半,主要就是用一個(gè)變量、表達(dá)式、while循環(huán)、和重定向輸出到test.txt文件即可,代碼如下
#!/bin/bash
#create 5000 email acounts from 'test1@126.com 123456' to 'test5000@126.com 123456'
i=1
while [ "$i" -le 5000 ]
do
echo "test$i@126.com 123456" >> test.txt
i=`expr $i + 1`
done
用shell實(shí)現(xiàn)短得不能再短了,我答題的時(shí)候,也是用的shell實(shí)現(xiàn),shell對(duì)于一些簡(jiǎn)單的操作是很強(qiáng)大的,可謂殺人越貨,必備良藥啊
滑稽表情.png