用JAVA写向文本文件(InFile.txt)中写入一首唐诗与一段英文表达,并以自己的学号和 姓名结尾。显示文件的内容,并将 InFile 存放到 d:/目录下,最后将 InFile.txt 文 件的内容复制到另外一个目录下的 OutFile.txt 中。
时间: 2023-06-19 19:09:53 浏览: 100
以下是Java代码实现:
```java
import java.io.*;
public class FileIO {
public static void main(String[] args) {
String poem = "登高\n" +
"唐代:杜甫\n" +
"风急天高猿啸哀,\n" +
"渚清沙白鸟飞回。\n" +
"无边落木萧萧下,\n" +
"不尽长江滚滚来。\n" +
"万里悲秋常作客,\n" +
"百年多病独登台。\n" +
"艰难苦恨繁霜鬓,\n" +
"潦倒新停浊酒杯。\n\n";
String english = "The quick brown fox jumps over the lazy dog.\n\n";
String studentInfo = "学号:123456789\n姓名:张三\n";
// 写入文件
try {
File file = new File("d:/InFile.txt");
FileWriter writer = new FileWriter(file);
writer.write(poem);
writer.write(english);
writer.write(studentInfo);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
// 读取文件并输出内容
try {
File file = new File("d:/InFile.txt");
FileReader reader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
// 复制文件
try {
File inFile = new File("d:/InFile.txt");
File outFile = new File("d:/OutFile.txt");
FileReader fileReader = new FileReader(inFile);
BufferedReader bufferedReader = new BufferedReader(fileReader);
FileWriter fileWriter = new FileWriter(outFile);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
String line;
while ((line = bufferedReader.readLine()) != null) {
bufferedWriter.write(line);
bufferedWriter.newLine();
}
bufferedReader.close();
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
代码实现了以下功能:
1. 将一首唐诗和一段英文表达以及学号和姓名写入到 `d:/InFile.txt` 文件中。
2. 读取 `d:/InFile.txt` 文件的内容并输出。
3. 将 `d:/InFile.txt` 文件的内容复制到 `d:/OutFile.txt` 文件中。
阅读全文