Java 文件操作:字符串拼接、写入、读取和复制示例
Java 文件操作:字符串拼接、写入、读取和复制示例
本示例演示了使用 Java 进行文件操作的基本方法,包括将字符串拼接写入文件、读取文件内容和复制文件内容。代码使用字节流实现,并提供详细注释。
代码实现:
import java.io.*;
public class StringDemo {
public static void main(String[] args) {
try {
// 循环随机输入三段字符串
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
StringBuffer stringBuffer = new StringBuffer();
for (int i = 1; i <= 3; i++) {
System.out.println('请输入第' + i + '段字符串:');
String str = reader.readLine();
stringBuffer.append(str);
}
// 将拼接后的字符串写入文件
FileOutputStream fileOutputStream = new FileOutputStream('c:\inputDemo.txt');
fileOutputStream.write(stringBuffer.toString().getBytes());
fileOutputStream.close();
System.out.println('文件写入成功!');
// 读取文件内容并打印
FileInputStream fileInputStream = new FileInputStream('c:\inputDemo.txt');
byte[] bytes = new byte[fileInputStream.available()];
fileInputStream.read(bytes);
String content = new String(bytes);
System.out.println('文件内容为:' + content);
fileInputStream.close();
// 复制文件内容到另一个文件
FileInputStream fileInputStream2 = new FileInputStream('c:\inputDemo.txt');
FileOutputStream fileOutputStream2 = new FileOutputStream('c:\inputDemo2.txt');
byte[] bytes2 = new byte[fileInputStream2.available()];
fileInputStream2.read(bytes2);
fileOutputStream2.write(bytes2);
fileInputStream2.close();
fileOutputStream2.close();
System.out.println('文件复制成功!');
} catch (IOException e) {
e.printStackTrace();
}
}
}
代码功能说明:
- 循环随机输入三段字符串: 使用
BufferedReader从控制台读取用户输入的三段字符串,并使用StringBuffer将它们拼接起来。 - 将拼接后的字符串写入文件: 使用
FileOutputStream创建文件输出流,并使用write()方法将拼接后的字符串写入文件c:\inputDemo.txt。 - 读取文件内容并打印: 使用
FileInputStream创建文件输入流,使用available()方法获取文件大小,并使用read()方法将文件内容读入字节数组。最后将字节数组转换为字符串并打印出来。 - 复制文件内容到另一个文件: 使用
FileInputStream和FileOutputStream分别创建两个文件流,将第一个文件的内容读入字节数组,并写入到第二个文件。
注意:
- 代码中使用了
c:\inputDemo.txt和c:\inputDemo2.txt作为文件路径,请根据实际情况修改路径。 - 代码中使用了字节流进行文件操作,如果需要处理文本文件,可以使用字符流。
希望本示例能够帮助您理解 Java 文件操作的基本原理。
原文地址: https://www.cveoy.top/t/topic/op6Z 著作权归作者所有。请勿转载和采集!