利用Java编写两个线程,其一利用合适的文件流类把文件test.docx复制文件mytest.docx,其二统计文本文件myfile.txt中英文字母a-z出现的次数(不区分大小写),并输出统计结果;
时间: 2024-05-14 10:19:42 浏览: 76
好的,我明白了您的要求。下面是您提出的问题的答案:
问题1:
```java
import java.io.*;
public class CopyFileUsingThread {
public static void main(String[] args) {
Thread t1 = new Thread(new CopyFile());
Thread t2 = new Thread(new CountLetters());
t1.start();
t2.start();
}
}
class CopyFile implements Runnable {
@Override
public void run() {
FileInputStream is = null;
FileOutputStream os = null;
try {
is = new FileInputStream("test.docx");
os = new FileOutputStream("mytest.docx");
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
System.out.println("文件复制成功");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class CountLetters implements Runnable {
@Override
public void run() {
FileInputStream is = null;
try {
is = new FileInputStream("myfile.txt");
int[] count = new int[26];
int letterCount = 0;
int ch;
while ((ch = is.read()) != -1) {
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {
letterCount++;
if (ch >= 'a' && ch <= 'z') {
count[ch - 'a']++;
} else {
count[ch - 'A']++;
}
}
}
for (int i = 0; i < 26; i++) {
System.out.println((char)('a' + i) + ": " + count[i]);
}
System.out.println("字母总数:" + letterCount);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
```
问题2的代码使用了Java I/O类,它们在Java SE 11中已经被废弃,建议使用更现代的文件I/O类,例如NIO 2。
希望这个回答对您有所帮助,如您需要进一步的解释或者有其他问题,请随时联系我。
阅读全文