Java将C:\\abc\\1.txt中的文件中的文件信息”用户名:123,密码:123456“复制到C:\\abc\\2.txt文件中
时间: 2023-07-24 14:13:52 浏览: 59
您可以使用Java的文件输入输出流来实现这个功能。以下是一个示例代码:
```java
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
String sourceFilePath = "C:\\abc\\1.txt";
String destinationFilePath = "C:\\abc\\2.txt";
try {
FileReader fileReader = new FileReader(sourceFilePath);
BufferedReader bufferedReader = new BufferedReader(fileReader);
FileWriter fileWriter = new FileWriter(destinationFilePath);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
String line;
while ((line = bufferedReader.readLine()) != null) {
if (line.contains("用户名") && line.contains("密码")) {
bufferedWriter.write(line + System.lineSeparator());
}
}
bufferedReader.close();
bufferedWriter.close();
System.out.println("文件信息已复制至 " + destinationFilePath);
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
这段代码将源文件路径设为"C:\\abc\\1.txt",将目标文件路径设为"C:\\abc\\2.txt"。请根据您的实际需求进行修改。在运行代码后,它将读取源文件的内容并检查每一行是否包含"用户名"和"密码"。如果是,则将该行写入目标文件中。注意,这里使用了缓冲读写流来提高性能。最后,它会关闭读写流并输出成功消息。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)