62,614
社区成员
发帖
与我相关
我的任务
分享
import java.io.*;
import java.util.Random;
import java.util.Scanner;
public class Exercise_12_15 {
//实例化File类的的对象,类的文件名是Exercise12_15.txt。
private static File thefile = new File("j:/Exercise12_15.txt");
public static void main(String[] args) throws IOException {
myPrint();
}
private static void myScanner() throws FileNotFoundException {
//扫描Exercise12_15.txt文件。把文件每一行打印到控制台。
try (Scanner readfromtxt = new Scanner(thefile)) {
while (readfromtxt.hasNextLine()) {
System.out.println(readfromtxt.nextLine());
}
}
}
private static void myPrint() throws FileNotFoundException {
//调用myScanner方法,如果没有找到Exercise12_15.txt,则捕获这个异常。
try {
myScanner();
System.out.println(thefile.getName() + "文件已存在。");
} catch (FileNotFoundException ex) { // 没有文件的异常被捕获。
Random myrnd = new Random(); // 实例化Random类的对象。
int[] rndInt = new int[15]; // 声明数组。
for (int i = 0; i < rndInt.length - 1; i++) { // 数组元素赋值。
rndInt[i] = myrnd.nextInt(100);
}
//创建Exercise12_15.txt文件,把数组内容写进去。
try (PrintWriter writetotxt = new PrintWriter(thefile)) {
for (int i = 0; i < rndInt.length - 1; i++) {
writetotxt.println(rndInt[i]);
}
}
myScanner();
}
}
}