1.从键盘读入10个整数,然后将它们从小到大排序并写入文件c1.txt,然后再将文件的内容读出来,输出到屏幕上。 2.读取某个路径下的所有文本文件中内容,并将其存储在另一个文本文件中存放。 “D:\\www” File f=new File(“D:\\www”);
时间: 2023-12-14 16:38:06 浏览: 58
1. 代码如下:
```java
import java.io.*;
import java.util.Arrays;
public class SortAndWriteToFile {
public static void main(String[] args) {
int[] nums = new int[10];
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try {
for (int i = 0; i < 10; i++) {
nums[i] = Integer.parseInt(reader.readLine());
}
Arrays.sort(nums);
File file = new File("c1.txt");
FileWriter writer = new FileWriter(file);
for (int i = 0; i < 10; i++) {
writer.write(nums[i] + "\n");
}
writer.close();
BufferedReader fileReader = new BufferedReader(new FileReader(file));
String line;
while ((line = fileReader.readLine()) != null) {
System.out.println(line);
}
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
2. 代码如下:
```java
import java.io.*;
public class MergeFiles {
public static void main(String[] args) {
File folder = new File("D:\\www");
File outputFile = new File("output.txt");
FileWriter writer;
try {
writer = new FileWriter(outputFile);
for (File file : folder.listFiles()) {
if (file.isFile() && file.getName().endsWith(".txt")) {
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
writer.write(line + "\n");
}
reader.close();
}
}
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
阅读全文