(1)分别使用FileWriter 和 BufferedWriter 往文件exp5_1.txt和文件exp5_2.txt中写入1万个随机整数(数与数之间用空格隔开),并在控制台上显示程序运行的时间。(exp5_1.java)(2)请使用字节流的方式读出文件exp5_1.txt中内容,然后将文件中的所有奇数写入文件ex5_3.txt中,使用字符流的方式读出文件exp5_2.txt中内容,然后将文件中的所有偶数写入文件exp5_4.txt中。(exp4_2.java) (3)请使用File类的相关方法,遍历(1)、(2)两题所读写的文件所在的目录下的所有文件。(exp5_3.java)
时间: 2024-02-01 20:13:47 浏览: 70
(1)exp5_1.java
```
import java.io.*;
import java.util.Random;
public class exp5_1 {
public static void main(String[] args) {
long start = System.currentTimeMillis();
try {
FileWriter fw = new FileWriter("exp5_1.txt");
BufferedWriter bw = new BufferedWriter(fw);
Random random = new Random();
for (int i = 0; i < 10000; i++) {
int num = random.nextInt();
bw.write(num + " ");
}
bw.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
long end = System.currentTimeMillis();
System.out.println("程序运行时间:" + (end - start) + "ms");
start = System.currentTimeMillis();
try {
FileOutputStream fos = new FileOutputStream("exp5_2.txt");
OutputStreamWriter osw = new OutputStreamWriter(fos);
BufferedWriter bw = new BufferedWriter(osw);
Random random = new Random();
for (int i = 0; i < 10000; i++) {
int num = random.nextInt();
bw.write(num + " ");
}
bw.close();
osw.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
end = System.currentTimeMillis();
System.out.println("程序运行时间:" + (end - start) + "ms");
}
}
```
(2)exp5_2.java
```
import java.io.*;
public class exp5_2 {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("exp5_1.txt");
FileOutputStream fos = new FileOutputStream("exp5_3.txt");
int num;
while ((num = fis.read()) != -1) {
if (num % 2 != 0) {
fos.write(num);
fos.write(' ');
}
}
fis.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileReader fr = new FileReader("exp5_2.txt");
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter("exp5_4.txt");
BufferedWriter bw = new BufferedWriter(fw);
String line;
while ((line = br.readLine()) != null) {
String[] nums = line.split(" ");
for (String num : nums) {
int n = Integer.parseInt(num);
if (n % 2 == 0) {
bw.write(num + " ");
}
}
}
br.close();
fr.close();
bw.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
(3)exp5_3.java
```
import java.io.File;
public class exp5_3 {
public static void main(String[] args) {
File file = new File(".");
File[] files = file.listFiles();
for (File f : files) {
System.out.println(f.getName());
}
}
}
```
阅读全文