1、创建类TimerAlarm,让它继承Thread并实现一个秒表的功能,不要使用内置的Timer类,程序运行的结果应该如下图所示:先按照时:分:秒打印时间,然后换一行打印总的秒数。 2、使用输入输出流,将文件words.txt 文件内容读出,然后以倒序的方式重新保存在信的文件newwords.txt里面,并为每个单词编号。如果在保存的时候newwords文件已经存在,应该产生FileFundException,并将其捕获处理
时间: 2023-06-19 14:05:17 浏览: 106
1. TimerAlarm代码如下:
```java
public class TimerAlarm extends Thread {
private int hours = 0;
private int minutes = 0;
private int seconds = 0;
private int totalSeconds = 0;
private boolean running = true;
@Override
public void run() {
while (running) {
try {
Thread.sleep(1000);
seconds++;
if (seconds == 60) {
seconds = 0;
minutes++;
}
if (minutes == 60) {
minutes = 0;
hours++;
}
System.out.printf("%02d:%02d:%02d\n", hours, minutes, seconds);
totalSeconds++;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Total seconds: " + totalSeconds);
}
public void stopTimer() {
running = false;
}
}
```
2. 读取words.txt并倒序保存到newwords.txt代码如下:
```java
import java.io.*;
public class ReverseWords {
public static void main(String[] args) {
try {
BufferedReader reader = new BufferedReader(new FileReader("words.txt"));
String line;
StringBuilder content = new StringBuilder();
while ((line = reader.readLine()) != null) {
content.append(line).append("\n");
}
reader.close();
String[] words = content.toString().split("\\s+");
StringBuilder reverseContent = new StringBuilder();
for (int i = words.length - 1; i >= 0; i--) {
reverseContent.append(i + 1).append(". ").append(words[i]).append("\n");
}
File newWordsFile = new File("newwords.txt");
if (newWordsFile.exists()) {
throw new FileFoundException("File already exists!");
}
BufferedWriter writer = new BufferedWriter(new FileWriter(newWordsFile));
writer.write(reverseContent.toString());
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (FileFoundException e) {
e.printStackTrace();
}
}
}
class FileFoundException extends Exception {
public FileFoundException(String message) {
super(message);
}
}
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)