1.从键盘读入10个整数,然后将它们从小到大排序并写入文件c1.txt,然后再将文件的内容读出来,输出到屏幕上。 2.读取某个路径下的所有文本文件中内容,并将其存储在另一个文本文件中存放。 “D:\\www” File f=new File(“D:\\www”);
时间: 2023-12-14 11:39:55 浏览: 72
C++_中关于文件的读入和输出
1. 实现代码如下:
```java
import java.io.*;
import java.util.*;
public class SortAndWrite {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] nums = new int[10];
System.out.println("请输入10个整数:");
for (int i = 0; i < 10; i++) {
nums[i] = scanner.nextInt();
}
Arrays.sort(nums);
try {
FileWriter fw = new FileWriter("c1.txt");
for (int i : nums) {
fw.write(i + " ");
}
fw.close();
FileReader fr = new FileReader("c1.txt");
BufferedReader br = new BufferedReader(fr);
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
2. 实现代码如下:
```java
import java.io.*;
import java.util.*;
public class MergeFiles {
public static void main(String[] args) {
String path = "D:\\www";
String outputPath = "output.txt";
File dir = new File(path);
if (!dir.isDirectory()) {
System.out.println(path + "不是一个目录!");
return;
}
try {
FileWriter fw = new FileWriter(outputPath);
BufferedWriter bw = new BufferedWriter(fw);
File[] files = dir.listFiles();
for (File file : files) {
if (file.isFile()) {
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line = null;
while ((line = br.readLine()) != null) {
bw.write(line);
bw.newLine();
}
br.close();
fr.close();
}
}
bw.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
阅读全文